home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / man / cmds.fmt / perl.man < prev    next >
Encoding:
Text File  |  1991-11-15  |  238.5 KB  |  7,129 lines

  1.  
  2.  
  3.  
  4. PERL                      User Commands                      PERL
  5.  
  6.  
  7.  
  8. NNAAMMEE
  9.      perl - Practical Extraction and Report Language
  10.  
  11. SSYYNNOOPPSSIISS
  12.      ppeerrll [options] filename args
  13.  
  14. DDEESSCCRRIIPPTTIIOONN
  15.      _P_e_r_l is an interpreted language optimized for scanning arbi-
  16.      trary text files, extracting information from those text
  17.      files, and printing reports based on that information.  It's
  18.      also a good language for many system management tasks.  The
  19.      language is intended to be practical (easy to use, effi-
  20.      cient, complete) rather than beautiful (tiny, elegant,
  21.      minimal).  It combines (in the author's opinion, anyway)
  22.      some of the best features of C, _s_e_d, _a_w_k, and _s_h, so people
  23.      familiar with those languages should have little difficulty
  24.      with it.  (Language historians will also note some vestiges
  25.      of _c_s_h, Pascal, and even BASIC-PLUS.) Expression syntax
  26.      corresponds quite closely to C expression syntax.  Unlike
  27.      most Unix utilities, _p_e_r_l does not arbitrarily limit the
  28.      size of your data--if you've got the memory, _p_e_r_l can slurp
  29.      in your whole file as a single string.  Recursion is of
  30.      unlimited depth.  And the hash tables used by associative
  31.      arrays grow as necessary to prevent degraded performance.
  32.      _P_e_r_l uses sophisticated pattern matching techniques to scan
  33.      large amounts of data very quickly.  Although optimized for
  34.      scanning text, _p_e_r_l can also deal with binary data, and can
  35.      make dbm files look like associative arrays (where dbm is
  36.      available).  Setuid _p_e_r_l scripts are safer than C programs
  37.      through a dataflow tracing mechanism which prevents many
  38.      stupid security holes.  If you have a problem that would
  39.      ordinarily use _s_e_d or _a_w_k or _s_h, but it exceeds their capa-
  40.      bilities or must run a little faster, and you don't want to
  41.      write the silly thing in C, then _p_e_r_l may be for you.  There
  42.      are also translators to turn your _s_e_d and _a_w_k scripts into
  43.      _p_e_r_l scripts.  OK, enough hype.
  44.  
  45.      Upon startup, _p_e_r_l looks for your script in one of the fol-
  46.      lowing places:
  47.  
  48.      1.  Specified line by line via --ee switches on the command
  49.          line.
  50.  
  51.      2.  Contained in the file specified by the first filename on
  52.          the command line.  (Note that systems supporting the #!
  53.          notation invoke interpreters this way.)
  54.  
  55.      3.  Passed in implicitly via standard input.  This only
  56.          works if there are no filename arguments--to pass argu-
  57.          ments to a _s_t_d_i_n script you must explicitly specify a -
  58.          for the script name.
  59.  
  60.  
  61.  
  62.  
  63. Sprite v1.0                                                     1
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PERL                      User Commands                      PERL
  71.  
  72.  
  73.  
  74.      After locating your script, _p_e_r_l compiles it to an internal
  75.      form.  If the script is syntactically correct, it is exe-
  76.      cuted.
  77.  
  78.      OOppttiioonnss
  79.  
  80.      Note: on first reading this section may not make much sense
  81.      to you.  It's here at the front for easy reference.
  82.  
  83.      A single-character option may be combined with the following
  84.      option, if any.  This is particularly useful when invoking a
  85.      script using the #! construct which only allows one argu-
  86.      ment.  Example:
  87.  
  88.           #!/usr/bin/perl -spi.bak # same as -s -p -i.bak
  89.           ...
  90.  
  91.      Options include:
  92.  
  93.      --00_d_i_g_i_t_s
  94.           specifies the record separator ($/) as an octal number.
  95.           If there are no digits, the null character is the
  96.           separator.  Other switches may precede or follow the
  97.           digits.  For example, if you have a version of _f_i_n_d
  98.           which can print filenames terminated by the null char-
  99.           acter, you can say this:
  100.  
  101.               find . -name '*.bak' -print0 | perl -n0e unlink
  102.  
  103.           The special value 00 will cause Perl to slurp files in
  104.           paragraph mode.  The value 0777 will cause Perl to
  105.           slurp files whole since there is no legal character
  106.           with that value.
  107.  
  108.      --aa   turns on autosplit mode when used with a --nn or --pp.  An
  109.           implicit split command to the @F array is done as the
  110.           first thing inside the implicit while loop produced by
  111.           the --nn or --pp.
  112.  
  113.                perl -ane 'print pop(@F), "\n";'
  114.  
  115.           is equivalent to
  116.  
  117.                while (<>) {
  118.                     @F = split(' ');
  119.                     print pop(@F), "\n";
  120.                }
  121.  
  122.  
  123.      --cc   causes _p_e_r_l to check the syntax of the script and then
  124.           exit without executing it.
  125.  
  126.  
  127.  
  128.  
  129. Sprite v1.0                                                     2
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PERL                      User Commands                      PERL
  137.  
  138.  
  139.  
  140.      --dd   runs the script under the perl debugger.  See the sec-
  141.           tion on Debugging.
  142.  
  143.      --DD_n_u_m_b_e_r
  144.           sets debugging flags.  To watch how it executes your
  145.           script, use --DD1144.  (This only works if debugging is
  146.           compiled into your _p_e_r_l.) Another nice value is -D1024,
  147.           which lists your compiled syntax tree.  And -D512
  148.           displays compiled regular expressions.
  149.  
  150.      --ee _c_o_m_m_a_n_d_l_i_n_e
  151.           may be used to enter one line of script.  Multiple --ee
  152.           commands may be given to build up a multi-line script.
  153.           If --ee is given, _p_e_r_l will not look for a script
  154.           filename in the argument list.
  155.  
  156.      --ii_e_x_t_e_n_s_i_o_n
  157.           specifies that files processed by the <> construct are
  158.           to be edited in-place.  It does this by renaming the
  159.           input file, opening the output file by the same name,
  160.           and selecting that output file as the default for print
  161.           statements.  The extension, if supplied, is added to
  162.           the name of the old file to make a backup copy.  If no
  163.           extension is supplied, no backup is made.  Saying "perl
  164.           -p -i.bak -e "s/foo/bar/;" ... " is the same as using
  165.           the script:
  166.  
  167.                #!/usr/bin/perl -pi.bak
  168.                s/foo/bar/;
  169.  
  170.           which is equivalent to
  171.  
  172.                #!/usr/bin/perl
  173.                while (<>) {
  174.                     if ($ARGV ne $oldargv) {
  175.                          rename($ARGV, $ARGV . '.bak');
  176.                          open(ARGVOUT, ">$ARGV");
  177.                          select(ARGVOUT);
  178.                          $oldargv = $ARGV;
  179.                     }
  180.                     s/foo/bar/;
  181.                }
  182.                continue {
  183.                    print;     # this prints to original filename
  184.                }
  185.                select(STDOUT);
  186.  
  187.           except that the --ii form doesn't need to compare $ARGV
  188.           to $oldargv to know when the filename has changed.  It
  189.           does, however, use ARGVOUT for the selected filehandle.
  190.           Note that _S_T_D_O_U_T is restored as the default output
  191.           filehandle after the loop.
  192.  
  193.  
  194.  
  195. Sprite v1.0                                                     3
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PERL                      User Commands                      PERL
  203.  
  204.  
  205.  
  206.           You can use eof to locate the end of each input file,
  207.           in case you want to append to each file, or reset line
  208.           numbering (see example under eof).
  209.  
  210.      --II_d_i_r_e_c_t_o_r_y
  211.           may be used in conjunction with --PP to tell the C
  212.           preprocessor where to look for include files.  By
  213.           default /usr/include and /usr/lib/perl are searched.
  214.  
  215.      --ll_o_c_t_n_u_m
  216.           enables automatic line-ending processing.  It has two
  217.           effects: first, it automatically chops the line termi-
  218.           nator when used with --nn or --pp ,, and second, it assigns
  219.           $\ to have the value of _o_c_t_n_u_m so that any print state-
  220.           ments will have that line terminator added back on.  If
  221.           _o_c_t_n_u_m is omitted, sets $\ to the current value of $/.
  222.           For instance, to trim lines to 80 columns:
  223.  
  224.                perl -lpe 'substr($_, 80) = ""'
  225.  
  226.           Note that the assignment $\ = $/ is done when the
  227.           switch is processed, so the input record separator can
  228.           be different than the output record separator if the --ll
  229.           switch is followed by a --00 switch:
  230.  
  231.                gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
  232.  
  233.           This sets $\ to newline and then sets $/ to the null
  234.           character.
  235.  
  236.      --nn   causes _p_e_r_l to assume the following loop around your
  237.           script, which makes it iterate over filename arguments
  238.           somewhat like "sed -n" or _a_w_k:
  239.  
  240.                while (<>) {
  241.                     ...       # your script goes here
  242.                }
  243.  
  244.           Note that the lines are not printed by default.  See --pp
  245.           to have lines printed.  Here is an efficient way to
  246.           delete all files older than a week:
  247.  
  248.                find . -mtime +7 -print | perl -nle 'unlink;'
  249.  
  250.           This is faster than using the -exec switch of find
  251.           because you don't have to start a process on every
  252.           filename found.
  253.  
  254.      --pp   causes _p_e_r_l to assume the following loop around your
  255.           script, which makes it iterate over filename arguments
  256.           somewhat like _s_e_d:
  257.  
  258.  
  259.  
  260.  
  261. Sprite v1.0                                                     4
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PERL                      User Commands                      PERL
  269.  
  270.  
  271.  
  272.                while (<>) {
  273.                     ...       # your script goes here
  274.                } continue {
  275.                     print;
  276.                }
  277.  
  278.           Note that the lines are printed automatically.  To
  279.           suppress printing use the --nn switch.  A --pp overrides a
  280.           --nn switch.
  281.  
  282.      --PP   causes your script to be run through the C preprocessor
  283.           before compilation by _p_e_r_l.  (Since both comments and
  284.           cpp directives begin with the # character, you should
  285.           avoid starting comments with any words recognized by
  286.           the C preprocessor such as "if", "else" or "define".)
  287.  
  288.      --ss   enables some rudimentary switch parsing for switches on
  289.           the command line after the script name but before any
  290.           filename arguments (or before a --).  Any switch found
  291.           there is removed from @ARGV and sets the corresponding
  292.           variable in the _p_e_r_l script.  The following script
  293.           prints "true" if and only if the script is invoked with
  294.           a -xyz switch.
  295.  
  296.                #!/usr/bin/perl -s
  297.                if ($xyz) { print "true\n"; }
  298.  
  299.  
  300.      --SS   makes _p_e_r_l use the PATH environment variable to search
  301.           for the script (unless the name of the script starts
  302.           with a slash).  Typically this is used to emulate #!
  303.           startup on machines that don't support #!, in the fol-
  304.           lowing manner:
  305.  
  306.                #!/usr/bin/perl
  307.                eval "exec /usr/bin/perl -S $0 $*"
  308.                     if $running_under_some_shell;
  309.  
  310.           The system ignores the first line and feeds the script
  311.           to /bin/sh, which proceeds to try to execute the _p_e_r_l
  312.           script as a shell script.  The shell executes the
  313.           second line as a normal shell command, and thus starts
  314.           up the _p_e_r_l interpreter.  On some systems $0 doesn't
  315.           always contain the full pathname, so the --SS tells _p_e_r_l
  316.           to search for the script if necessary.  After _p_e_r_l
  317.           locates the script, it parses the lines and ignores
  318.           them because the variable $running_under_some_shell is
  319.           never true.  A better construct than $* would be
  320.           ${1+"$@"}, which handles embedded spaces and such in
  321.           the filenames, but doesn't work if the script is being
  322.           interpreted by csh.  In order to start up sh rather
  323.           than csh, some systems may have to replace the #! line
  324.  
  325.  
  326.  
  327. Sprite v1.0                                                     5
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PERL                      User Commands                      PERL
  335.  
  336.  
  337.  
  338.           with a line containing just a colon, which will be pol-
  339.           itely ignored by perl.  Other systems can't control
  340.           that, and need a totally devious construct that will
  341.           work under any of csh, sh or perl, such as the follow-
  342.           ing:
  343.  
  344.                eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  345.                & eval 'exec /usr/bin/perl -S $0 $argv:q'
  346.                     if 0;
  347.  
  348.  
  349.      --uu   causes _p_e_r_l to dump core after compiling your script.
  350.           You can then take this core dump and turn it into an
  351.           executable file by using the undump program (not sup-
  352.           plied).  This speeds startup at the expense of some
  353.           disk space (which you can minimize by stripping the
  354.           executable).  (Still, a "hello world" executable comes
  355.           out to about 200K on my machine.) If you are going to
  356.           run your executable as a set-id program then you should
  357.           probably compile it using taintperl rather than normal
  358.           perl.  If you want to execute a portion of your script
  359.           before dumping, use the dump operator instead.  Note:
  360.           availability of undump is platform specific and may not
  361.           be available for a specific port of perl.
  362.  
  363.      --UU   allows _p_e_r_l to do unsafe operations.  Currently the
  364.           only "unsafe" operations are the unlinking of direc-
  365.           tories while running as superuser, and running setuid
  366.           programs with fatal taint checks turned into warnings.
  367.  
  368.      --vv   prints the version and patchlevel of your _p_e_r_l execut-
  369.           able.
  370.  
  371.      --ww   prints warnings about identifiers that are mentioned
  372.           only once, and scalar variables that are used before
  373.           being set.  Also warns about redefined subroutines, and
  374.           references to undefined filehandles or filehandles
  375.           opened readonly that you are attempting to write on.
  376.           Also warns you if you use == on values that don't look
  377.           like numbers, and if your subroutines recurse more than
  378.           100 deep.
  379.  
  380.      --xx_d_i_r_e_c_t_o_r_y
  381.           tells _p_e_r_l that the script is embedded in a message.
  382.           Leading garbage will be discarded until the first line
  383.           that starts with #! and contains the string "perl".
  384.           Any meaningful switches on that line will be applied
  385.           (but only one group of switches, as with normal #! pro-
  386.           cessing).  If a directory name is specified, Perl will
  387.           switch to that directory before running the script.
  388.           The --xx switch only controls the the disposal of leading
  389.           garbage.  The script must be terminated with __END__ if
  390.  
  391.  
  392.  
  393. Sprite v1.0                                                     6
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PERL                      User Commands                      PERL
  401.  
  402.  
  403.  
  404.           there is trailing garbage to be ignored (the script can
  405.           process any or all of the trailing garbage via the DATA
  406.           filehandle if desired).
  407.  
  408.      DDaattaa TTyyppeess aanndd OObbjjeeccttss
  409.  
  410.      _P_e_r_l has three data types: scalars, arrays of scalars, and
  411.      associative arrays of scalars.  Normal arrays are indexed by
  412.      number, and associative arrays by string.
  413.  
  414.      The interpretation of operations and values in perl some-
  415.      times depends on the requirements of the context around the
  416.      operation or value.  There are three major contexts: string,
  417.      numeric and array.  Certain operations return array values
  418.      in contexts wanting an array, and scalar values otherwise.
  419.      (If this is true of an operation it will be mentioned in the
  420.      documentation for that operation.) Operations which return
  421.      scalars don't care whether the context is looking for a
  422.      string or a number, but scalar variables and values are
  423.      interpreted as strings or numbers as appropriate to the con-
  424.      text.  A scalar is interpreted as TRUE in the boolean sense
  425.      if it is not the null string or 0.  Booleans returned by
  426.      operators are 1 for true and 0 or '' (the null string) for
  427.      false.
  428.  
  429.      There are actually two varieties of null string: defined and
  430.      undefined.  Undefined null strings are returned when there
  431.      is no real value for something, such as when there was an
  432.      error, or at end of file, or when you refer to an uninitial-
  433.      ized variable or element of an array.  An undefined null
  434.      string may become defined the first time you access it, but
  435.      prior to that you can use the defined() operator to deter-
  436.      mine whether the value is defined or not.
  437.  
  438.      References to scalar variables always begin with '$', even
  439.      when referring to a scalar that is part of an array.  Thus:
  440.  
  441.          $days           # a simple scalar variable
  442.          $days[28]       # 29th element of array @days
  443.          $days{'Feb'}    # one value from an associative array
  444.          $#days          # last index of array @days
  445.  
  446.      but entire arrays or array slices are denoted by '@':
  447.  
  448.          @days           # ($days[0], $days[1],... $days[n])
  449.          @days[3,4,5]    # same as @days[3..5]
  450.          @days{'a','c'}  # same as ($days{'a'},$days{'c'})
  451.  
  452.      and entire associative arrays are denoted by '%':
  453.  
  454.          %days           # (key1, val1, key2, val2 ...)
  455.  
  456.  
  457.  
  458.  
  459. Sprite v1.0                                                     7
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PERL                      User Commands                      PERL
  467.  
  468.  
  469.  
  470.      Any of these eight constructs may serve as an lvalue, that
  471.      is, may be assigned to.  (It also turns out that an assign-
  472.      ment is itself an lvalue in certain contexts--see examples
  473.      under s, tr and chop.) Assignment to a scalar evaluates the
  474.      righthand side in a scalar context, while assignment to an
  475.      array or array slice evaluates the righthand side in an
  476.      array context.
  477.  
  478.      You may find the length of array @days by evaluating
  479.      "$#days", as in _c_s_h.  (Actually, it's not the length of the
  480.      array, it's the subscript of the last element, since there
  481.      is (ordinarily) a 0th element.) Assigning to $#days changes
  482.      the length of the array.  Shortening an array by this method
  483.      does not actually destroy any values.  Lengthening an array
  484.      that was previously shortened recovers the values that were
  485.      in those elements.  You can also gain some measure of effi-
  486.      ciency by preextending an array that is going to get big.
  487.      (You can also extend an array by assigning to an element
  488.      that is off the end of the array.  This differs from assign-
  489.      ing to $#whatever in that intervening values are set to null
  490.      rather than recovered.) You can truncate an array down to
  491.      nothing by assigning the null list () to it.  The following
  492.      are exactly equivalent
  493.  
  494.           @whatever = ();
  495.           $#whatever = $[ - 1;
  496.  
  497.  
  498.      If you evaluate an array in a scalar context, it returns the
  499.      length of the array.  The following is always true:
  500.  
  501.           scalar(@whatever) == $#whatever - $[ + 1;
  502.  
  503.      If you evaluate an associative array in a scalar context, it
  504.      returns a value which is true if and only if the array con-
  505.      tains any elements.  (If there are any elements, the value
  506.      returned is a string consisting of the number of used buck-
  507.      ets and the number of allocated buckets, separated by a
  508.      slash.)
  509.  
  510.      Multi-dimensional arrays are not directly supported, but see
  511.      the discussion of the $; variable later for a means of emu-
  512.      lating multiple subscripts with an associative array.  You
  513.      could also write a subroutine to turn multiple subscripts
  514.      into a single subscript.
  515.  
  516.      Every data type has its own namespace.  You can, without
  517.      fear of conflict, use the same name for a scalar variable,
  518.      an array, an associative array, a filehandle, a subroutine
  519.      name, and/or a label.  Since variable and array references
  520.      always start with '$', '@', or '%', the "reserved" words
  521.      aren't in fact reserved with respect to variable names.
  522.  
  523.  
  524.  
  525. Sprite v1.0                                                     8
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PERL                      User Commands                      PERL
  533.  
  534.  
  535.  
  536.      (They ARE reserved with respect to labels and filehandles,
  537.      however, which don't have an initial special character.
  538.      Hint: you could say open(LOG,'logfile') rather than
  539.      open(log,'logfile').  Using uppercase filehandles also
  540.      improves readability and protects you from conflict with
  541.      future reserved words.) Case IS significant--"FOO", "Foo"
  542.      and "foo" are all different names.  Names which start with a
  543.      letter may also contain digits and underscores.  Names which
  544.      do not start with a letter are limited to one character,
  545.      e.g. "$%" or "$$".  (Most of the one character names have a
  546.      predefined significance to _p_e_r_l.  More later.)
  547.  
  548.      Numeric literals are specified in any of the usual floating
  549.      point or integer formats:
  550.  
  551.          12345
  552.          12345.67
  553.          .23E-10
  554.          0xffff     # hex
  555.          0377  # octal
  556.  
  557.      String literals are delimited by either single or double
  558.      quotes.  They work much like shell quotes: double-quoted
  559.      string literals are subject to backslash and variable sub-
  560.      stitution; single-quoted strings are not (except for \' and
  561.      \\).  The usual backslash rules apply for making characters
  562.      such as newline, tab, etc., as well as some more exotic
  563.      forms:
  564.  
  565.           \t        tab
  566.           \n        newline
  567.           \r        return
  568.           \f        form feed
  569.           \b        backspace
  570.           \a        alarm (bell)
  571.           \e        escape
  572.           \033      octal char
  573.           \x1b      hex char
  574.           \c[       control char
  575.           \l        lowercase next char
  576.           \u        uppercase next char
  577.           \L        lowercase till \E
  578.           \U        uppercase till \E
  579.           \E        end case modification
  580.  
  581.      You can also embed newlines directly in your strings, i.e.
  582.      they can end on a different line than they begin.  This is
  583.      nice, but if you forget your trailing quote, the error will
  584.      not be reported until _p_e_r_l finds another line containing the
  585.      quote character, which may be much further on in the script.
  586.      Variable substitution inside strings is limited to scalar
  587.      variables, normal array values, and array slices.  (In other
  588.  
  589.  
  590.  
  591. Sprite v1.0                                                     9
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PERL                      User Commands                      PERL
  599.  
  600.  
  601.  
  602.      words, identifiers beginning with $ or @, followed by an
  603.      optional bracketed expression as a subscript.) The following
  604.      code segment prints out "The price is $100."
  605.  
  606.          $Price = '$100';               # not interpreted
  607.          print "The price is $Price.\n";# interpreted
  608.  
  609.      Note that you can put curly brackets around the identifier
  610.      to delimit it from following alphanumerics.  Also note that
  611.      a single quoted string must be separated from a preceding
  612.      word by a space, since single quote is a valid character in
  613.      an identifier (see Packages).
  614.  
  615.      Two special literals are __LINE__ and __FILE__, which
  616.      represent the current line number and filename at that point
  617.      in your program.  They may only be used as separate tokens;
  618.      they will not be interpolated into strings.  In addition,
  619.      the token __END__ may be used to indicate the logical end of
  620.      the script before the actual end of file.  Any following
  621.      text is ignored (but may be read via the DATA filehandle).
  622.      The two control characters ^D and ^Z are synonyms for
  623.      __END__.
  624.  
  625.      A word that doesn't have any other interpretation in the
  626.      grammar will be treated as if it had single quotes around
  627.      it.  For this purpose, a word consists only of alphanumeric
  628.      characters and underline, and must start with an alphabetic
  629.      character.  As with filehandles and labels, a bare word that
  630.      consists entirely of lowercase letters risks conflict with
  631.      future reserved words, and if you use the --ww switch, Perl
  632.      will warn you about any such words.
  633.  
  634.      Array values are interpolated into double-quoted strings by
  635.      joining all the elements of the array with the delimiter
  636.      specified in the $" variable, space by default.  (Since in
  637.      versions of perl prior to 3.0 the @ character was not a
  638.      metacharacter in double-quoted strings, the interpolation of
  639.      @array, $array[EXPR], @array[LIST], $array{EXPR}, or
  640.      @array{LIST} only happens if array is referenced elsewhere
  641.      in the program or is predefined.) The following are
  642.      equivalent:
  643.  
  644.           $temp = join($",@ARGV);
  645.           system "echo $temp";
  646.  
  647.           system "echo @ARGV";
  648.  
  649.      Within search patterns (which also undergo double-quotish
  650.      substitution) there is a bad ambiguity:  Is /$foo[bar]/ to
  651.      be interpreted as /${foo}[bar]/ (where [bar] is a character
  652.      class for the regular expression) or as /${foo[bar]}/ (where
  653.      [bar] is the subscript to array @foo)?  If @foo doesn't
  654.  
  655.  
  656.  
  657. Sprite v1.0                                                    10
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PERL                      User Commands                      PERL
  665.  
  666.  
  667.  
  668.      otherwise exist, then it's obviously a character class.  If
  669.      @foo exists, perl takes a good guess about [bar], and is
  670.      almost always right.  If it does guess wrong, or if you're
  671.      just plain paranoid, you can force the correct interpreta-
  672.      tion with curly brackets as above.
  673.  
  674.      A line-oriented form of quoting is based on the shell here-
  675.      is syntax.  Following a << you specify a string to terminate
  676.      the quoted material, and all lines following the current
  677.      line down to the terminating string are the value of the
  678.      item.  The terminating string may be either an identifier (a
  679.      word), or some quoted text.  If quoted, the type of quotes
  680.      you use determines the treatment of the text, just as in
  681.      regular quoting.  An unquoted identifier works like double
  682.      quotes.  There must be no space between the << and the iden-
  683.      tifier.  (If you put a space it will be treated as a null
  684.      identifier, which is valid, and matches the first blank
  685.      line--see Merry Christmas example below.) The terminating
  686.      string must appear by itself (unquoted and with no surround-
  687.      ing whitespace) on the terminating line.
  688.  
  689.           print <<EOF;        # same as above
  690.      The price is $Price.
  691.      EOF
  692.  
  693.           print <<"EOF";      # same as above
  694.      The price is $Price.
  695.      EOF
  696.  
  697.           print << x 10;      # null identifier is delimiter
  698.      Merry Christmas!
  699.  
  700.           print <<`EOC`;      # execute commands
  701.      echo hi there
  702.      echo lo there
  703.      EOC
  704.  
  705.           print <<foo, <<bar; # you can stack them
  706.      I said foo.
  707.      foo
  708.      I said bar.
  709.      bar
  710.  
  711.      Array literals are denoted by separating individual values
  712.      by commas, and enclosing the list in parentheses:
  713.  
  714.           (LIST)
  715.  
  716.      In a context not requiring an array value, the value of the
  717.      array literal is the value of the final element, as in the C
  718.      comma operator.  For example,
  719.  
  720.  
  721.  
  722.  
  723. Sprite v1.0                                                    11
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PERL                      User Commands                      PERL
  731.  
  732.  
  733.  
  734.          @foo = ('cc', '-E', $bar);
  735.  
  736.      assigns the entire array value to array foo, but
  737.  
  738.          $foo = ('cc', '-E', $bar);
  739.  
  740.      assigns the value of variable bar to variable foo.  Note
  741.      that the value of an actual array in a scalar context is the
  742.      length of the array; the following assigns to $foo the value
  743.      3:
  744.  
  745.          @foo = ('cc', '-E', $bar);
  746.          $foo = @foo;         # $foo gets 3
  747.  
  748.      You may have an optional comma before the closing
  749.      parenthesis of an array literal, so that you can say:
  750.  
  751.          @foo = (
  752.           1,
  753.           2,
  754.           3,
  755.          );
  756.  
  757.      When a LIST is evaluated, each element of the list is
  758.      evaluated in an array context, and the resulting array value
  759.      is interpolated into LIST just as if each individual element
  760.      were a member of LIST.  Thus arrays lose their identity in a
  761.      LIST--the list
  762.  
  763.           (@foo,@bar,&SomeSub)
  764.  
  765.      contains all the elements of @foo followed by all the ele-
  766.      ments of @bar, followed by all the elements returned by the
  767.      subroutine named SomeSub.
  768.  
  769.      A list value may also be subscripted like a normal array.
  770.      Examples:
  771.  
  772.           $time = (stat($file))[8];     # stat returns array value
  773.           $digit = ('a','b','c','d','e','f')[$digit-10];
  774.           return (pop(@foo),pop(@foo))[0];
  775.  
  776.  
  777.      Array lists may be assigned to if and only if each element
  778.      of the list is an lvalue:
  779.  
  780.          ($a, $b, $c) = (1, 2, 3);
  781.  
  782.          ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  783.  
  784.      The final element may be an array or an associative array:
  785.  
  786.  
  787.  
  788.  
  789. Sprite v1.0                                                    12
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PERL                      User Commands                      PERL
  797.  
  798.  
  799.  
  800.          ($a, $b, @rest) = split;
  801.          local($a, $b, %rest) = @_;
  802.  
  803.      You can actually put an array anywhere in the list, but the
  804.      first array in the list will soak up all the values, and
  805.      anything after it will get a null value.  This may be useful
  806.      in a local().
  807.  
  808.      An associative array literal contains pairs of values to be
  809.      interpreted as a key and a value:
  810.  
  811.          # same as map assignment above
  812.          %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  813.  
  814.      Array assignment in a scalar context returns the number of
  815.      elements produced by the expression on the right side of the
  816.      assignment:
  817.  
  818.           $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
  819.  
  820.  
  821.      There are several other pseudo-literals that you should know
  822.      about.  If a string is enclosed by backticks (grave
  823.      accents), it first undergoes variable substitution just like
  824.      a double quoted string.  It is then interpreted as a com-
  825.      mand, and the output of that command is the value of the
  826.      pseudo-literal, like in a shell.  In a scalar context, a
  827.      single string consisting of all the output is returned.  In
  828.      an array context, an array of values is returned, one for
  829.      each line of output.  (You can set $/ to use a different
  830.      line terminator.) The command is executed each time the
  831.      pseudo-literal is evaluated.  The status value of the com-
  832.      mand is returned in $? (see Predefined Names for the
  833.      interpretation of $?).  Unlike in _c_s_h, no translation is
  834.      done on the return data--newlines remain newlines.  Unlike
  835.      in any of the shells, single quotes do not hide variable
  836.      names in the command from interpretation.  To pass a $
  837.      through to the shell you need to hide it with a backslash.
  838.  
  839.      Evaluating a filehandle in angle brackets yields the next
  840.      line from that file (newline included, so it's never false
  841.      until EOF, at which time an undefined value is returned).
  842.      Ordinarily you must assign that value to a variable, but
  843.      there is one situation where an automatic assignment hap-
  844.      pens.  If (and only if) the input symbol is the only thing
  845.      inside the conditional of a _w_h_i_l_e loop, the value is
  846.      automatically assigned to the variable "$_".  (This may seem
  847.      like an odd thing to you, but you'll use the construct in
  848.      almost every _p_e_r_l script you write.) Anyway, the following
  849.      lines are equivalent to each other:
  850.  
  851.  
  852.  
  853.  
  854.  
  855. Sprite v1.0                                                    13
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PERL                      User Commands                      PERL
  863.  
  864.  
  865.  
  866.          while ($_ = <STDIN>) { print; }
  867.          while (<STDIN>) { print; }
  868.          for (;<STDIN>;) { print; }
  869.          print while $_ = <STDIN>;
  870.          print while <STDIN>;
  871.  
  872.      The filehandles _S_T_D_I_N, _S_T_D_O_U_T and _S_T_D_E_R_R are predefined.
  873.      (The filehandles _s_t_d_i_n, _s_t_d_o_u_t and _s_t_d_e_r_r will also work
  874.      except in packages, where they would be interpreted as local
  875.      identifiers rather than global.) Additional filehandles may
  876.      be created with the _o_p_e_n function.
  877.  
  878.      If a <FILEHANDLE> is used in a context that is looking for
  879.      an array, an array consisting of all the input lines is
  880.      returned, one line per array element.  It's easy to make a
  881.      LARGE data space this way, so use with care.
  882.  
  883.      The null filehandle <> is special and can be used to emulate
  884.      the behavior of _s_e_d and _a_w_k.  Input from <> comes either
  885.      from standard input, or from each file listed on the command
  886.      line.  Here's how it works: the first time <> is evaluated,
  887.      the ARGV array is checked, and if it is null, $ARGV[0] is
  888.      set to '-', which when opened gives you standard input.  The
  889.      ARGV array is then processed as a list of filenames.  The
  890.      loop
  891.  
  892.           while (<>) {
  893.                ...            # code for each line
  894.           }
  895.  
  896.      is equivalent to
  897.  
  898.           unshift(@ARGV, '-') if $#ARGV < $[;
  899.           while ($ARGV = shift) {
  900.                open(ARGV, $ARGV);
  901.                while (<ARGV>) {
  902.                     ...       # code for each line
  903.                }
  904.           }
  905.  
  906.      except that it isn't as cumbersome to say.  It really does
  907.      shift array ARGV and put the current filename into variable
  908.      ARGV.  It also uses filehandle ARGV internally.  You can
  909.      modify @ARGV before the first <> as long as you leave the
  910.      first filename at the beginning of the array.  Line numbers
  911.      ($.) continue as if the input was one big happy file.  (But
  912.      see example under eof for how to reset line numbers on each
  913.      file.)
  914.  
  915.  
  916.  
  917.  
  918.  
  919.  
  920.  
  921. Sprite v1.0                                                    14
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PERL                      User Commands                      PERL
  929.  
  930.  
  931.  
  932.      If you want to set @ARGV to your own list of files, go right
  933.      ahead.  If you want to pass switches into your script, you
  934.      can put a loop on the front like this:
  935.  
  936.           while ($_ = $ARGV[0], /^-/) {
  937.                shift;
  938.               last if /^--$/;
  939.                /^-D(.*)/ && ($debug = $1);
  940.                /^-v/ && $verbose++;
  941.                ...       # other switches
  942.           }
  943.           while (<>) {
  944.                ...       # code for each line
  945.           }
  946.  
  947.      The <> symbol will return FALSE only once.  If you call it
  948.      again after this it will assume you are processing another
  949.      @ARGV list, and if you haven't set @ARGV, will input from
  950.      _S_T_D_I_N.
  951.  
  952.      If the string inside the angle brackets is a reference to a
  953.      scalar variable (e.g. <$foo>), then that variable contains
  954.      the name of the filehandle to input from.
  955.  
  956.      If the string inside angle brackets is not a filehandle, it
  957.      is interpreted as a filename pattern to be globbed, and
  958.      either an array of filenames or the next filename in the
  959.      list is returned, depending on context.  One level of $
  960.      interpretation is done first, but you can't say <$foo>
  961.      because that's an indirect filehandle as explained in the
  962.      previous paragraph.  You could insert curly brackets to
  963.      force interpretation as a filename glob: <${foo}>.  Example:
  964.  
  965.           while (<*.c>) {
  966.                chmod 0644, $_;
  967.           }
  968.  
  969.      is equivalent to
  970.  
  971.           open(foo, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  972.           while (<foo>) {
  973.                chop;
  974.                chmod 0644, $_;
  975.           }
  976.  
  977.      In fact, it's currently implemented that way.  (Which means
  978.      it will not work on filenames with spaces in them unless you
  979.      have /bin/csh on your machine.) Of course, the shortest way
  980.      to do the above is:
  981.  
  982.           chmod 0644, <*.c>;
  983.  
  984.  
  985.  
  986.  
  987. Sprite v1.0                                                    15
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PERL                      User Commands                      PERL
  995.  
  996.  
  997.  
  998.      SSyynnttaaxx
  999.  
  1000.      A _p_e_r_l script consists of a sequence of declarations and
  1001.      commands.  The only things that need to be declared in _p_e_r_l
  1002.      are report formats and subroutines.  See the sections below
  1003.      for more information on those declarations.  All uninitial-
  1004.      ized user-created objects are assumed to start with a null
  1005.      or 0 value until they are defined by some explicit operation
  1006.      such as assignment.  The sequence of commands is executed
  1007.      just once, unlike in _s_e_d and _a_w_k scripts, where the sequence
  1008.      of commands is executed for each input line.  While this
  1009.      means that you must explicitly loop over the lines of your
  1010.      input file (or files), it also means you have much more con-
  1011.      trol over which files and which lines you look at.  (Actu-
  1012.      ally, I'm lying--it is possible to do an implicit loop with
  1013.      either the --nn or --pp switch.)
  1014.  
  1015.      A declaration can be put anywhere a command can, but has no
  1016.      effect on the execution of the primary sequence of
  1017.      commands--declarations all take effect at compile time.
  1018.      Typically all the declarations are put at the beginning or
  1019.      the end of the script.
  1020.  
  1021.      _P_e_r_l is, for the most part, a free-form language.  (The only
  1022.      exception to this is format declarations, for fairly obvious
  1023.      reasons.) Comments are indicated by the # character, and
  1024.      extend to the end of the line.  If you attempt to use /* */
  1025.      C comments, it will be interpreted either as division or
  1026.      pattern matching, depending on the context.  So don't do
  1027.      that.
  1028.  
  1029.      CCoommppoouunndd ssttaatteemmeennttss
  1030.  
  1031.      In _p_e_r_l, a sequence of commands may be treated as one com-
  1032.      mand by enclosing it in curly brackets.  We will call this a
  1033.      BLOCK.
  1034.  
  1035.      The following compound commands may be used to control flow:
  1036.  
  1037.           if (EXPR) BLOCK
  1038.           if (EXPR) BLOCK else BLOCK
  1039.           if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  1040.           LABEL while (EXPR) BLOCK
  1041.           LABEL while (EXPR) BLOCK continue BLOCK
  1042.           LABEL for (EXPR; EXPR; EXPR) BLOCK
  1043.           LABEL foreach VAR (ARRAY) BLOCK
  1044.           LABEL BLOCK continue BLOCK
  1045.  
  1046.      Note that, unlike C and Pascal, these are defined in terms
  1047.      of BLOCKs, not statements.  This means that the curly brack-
  1048.      ets are _r_e_q_u_i_r_e_d--no dangling statements allowed.  If you
  1049.      want to write conditionals without curly brackets there are
  1050.  
  1051.  
  1052.  
  1053. Sprite v1.0                                                    16
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. PERL                      User Commands                      PERL
  1061.  
  1062.  
  1063.  
  1064.      several other ways to do it.  The following all do the same
  1065.      thing:
  1066.  
  1067.           if (!open(foo)) { die "Can't open $foo: $!"; }
  1068.           die "Can't open $foo: $!" unless open(foo);
  1069.           open(foo) || die "Can't open $foo: $!"; # foo or bust!
  1070.           open(foo) ? 'hi mom' : die "Can't open $foo: $!";
  1071.                          # a bit exotic, that last one
  1072.  
  1073.  
  1074.      The _i_f statement is straightforward.  Since BLOCKs are
  1075.      always bounded by curly brackets, there is never any ambi-
  1076.      guity about which _i_f an _e_l_s_e goes with.  If you use _u_n_l_e_s_s
  1077.      in place of _i_f, the sense of the test is reversed.
  1078.  
  1079.      The _w_h_i_l_e statement executes the block as long as the
  1080.      expression is true (does not evaluate to the null string or
  1081.      0).  The LABEL is optional, and if present, consists of an
  1082.      identifier followed by a colon.  The LABEL identifies the
  1083.      loop for the loop control statements _n_e_x_t, _l_a_s_t, and _r_e_d_o
  1084.      (see below).  If there is a _c_o_n_t_i_n_u_e BLOCK, it is always
  1085.      executed just before the conditional is about to be
  1086.      evaluated again, similarly to the third part of a _f_o_r loop
  1087.      in C.  Thus it can be used to increment a loop variable,
  1088.      even when the loop has been continued via the _n_e_x_t statement
  1089.      (similar to the C "continue" statement).
  1090.  
  1091.      If the word _w_h_i_l_e is replaced by the word _u_n_t_i_l, the sense
  1092.      of the test is reversed, but the conditional is still tested
  1093.      before the first iteration.
  1094.  
  1095.      In either the _i_f or the _w_h_i_l_e statement, you may replace
  1096.      "(EXPR)" with a BLOCK, and the conditional is true if the
  1097.      value of the last command in that block is true.
  1098.  
  1099.      The _f_o_r loop works exactly like the corresponding _w_h_i_l_e
  1100.      loop:
  1101.  
  1102.           for ($i = 1; $i < 10; $i++) {
  1103.                ...
  1104.           }
  1105.  
  1106.      is the same as
  1107.  
  1108.           $i = 1;
  1109.           while ($i < 10) {
  1110.                ...
  1111.           } continue {
  1112.                $i++;
  1113.           }
  1114.  
  1115.      The foreach loop iterates over a normal array value and sets
  1116.  
  1117.  
  1118.  
  1119. Sprite v1.0                                                    17
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. PERL                      User Commands                      PERL
  1127.  
  1128.  
  1129.  
  1130.      the variable VAR to be each element of the array in turn.
  1131.      The variable is implicitly local to the loop, and regains
  1132.      its former value upon exiting the loop.  The "foreach" key-
  1133.      word is actually identical to the "for" keyword, so you can
  1134.      use "foreach" for readability or "for" for brevity.  If VAR
  1135.      is omitted, $_ is set to each value.  If ARRAY is an actual
  1136.      array (as opposed to an expression returning an array
  1137.      value), you can modify each element of the array by modify-
  1138.      ing VAR inside the loop.  Examples:
  1139.  
  1140.           for (@ary) { s/foo/bar/; }
  1141.  
  1142.           foreach $elem (@elements) {
  1143.                $elem *= 2;
  1144.           }
  1145.  
  1146.           for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) {
  1147.                print $_, "\n"; sleep(1);
  1148.           }
  1149.  
  1150.           for (1..15) { print "Merry Christmas\n"; }
  1151.  
  1152.           foreach $item (split(/:[\\\n:]*/, $ENV{'TERMCAP'})) {
  1153.                print "Item: $item\n";
  1154.           }
  1155.  
  1156.  
  1157.      The BLOCK by itself (labeled or not) is equivalent to a loop
  1158.      that executes once.  Thus you can use any of the loop con-
  1159.      trol statements in it to leave or restart the block.  The
  1160.      _c_o_n_t_i_n_u_e block is optional.  This construct is particularly
  1161.      nice for doing case structures.
  1162.  
  1163.           foo: {
  1164.                if (/^abc/) { $abc = 1; last foo; }
  1165.                if (/^def/) { $def = 1; last foo; }
  1166.                if (/^xyz/) { $xyz = 1; last foo; }
  1167.                $nothing = 1;
  1168.           }
  1169.  
  1170.      There is no official switch statement in perl, because there
  1171.      are already several ways to write the equivalent.  In addi-
  1172.      tion to the above, you could write
  1173.  
  1174.           foo: {
  1175.                $abc = 1, last foo  if /^abc/;
  1176.                $def = 1, last foo  if /^def/;
  1177.                $xyz = 1, last foo  if /^xyz/;
  1178.                $nothing = 1;
  1179.           }
  1180.  
  1181.      or
  1182.  
  1183.  
  1184.  
  1185. Sprite v1.0                                                    18
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. PERL                      User Commands                      PERL
  1193.  
  1194.  
  1195.  
  1196.           foo: {
  1197.                /^abc/ && do { $abc = 1; last foo; };
  1198.                /^def/ && do { $def = 1; last foo; };
  1199.                /^xyz/ && do { $xyz = 1; last foo; };
  1200.                $nothing = 1;
  1201.           }
  1202.  
  1203.      or
  1204.  
  1205.           foo: {
  1206.                /^abc/ && ($abc = 1, last foo);
  1207.                /^def/ && ($def = 1, last foo);
  1208.                /^xyz/ && ($xyz = 1, last foo);
  1209.                $nothing = 1;
  1210.           }
  1211.  
  1212.      or even
  1213.  
  1214.           if (/^abc/)
  1215.                { $abc = 1; }
  1216.           elsif (/^def/)
  1217.                { $def = 1; }
  1218.           elsif (/^xyz/)
  1219.                { $xyz = 1; }
  1220.           else
  1221.                {$nothing = 1;}
  1222.  
  1223.      As it happens, these are all optimized internally to a
  1224.      switch structure, so perl jumps directly to the desired
  1225.      statement, and you needn't worry about perl executing a lot
  1226.      of unnecessary statements when you have a string of 50
  1227.      elsifs, as long as you are testing the same simple scalar
  1228.      variable using ==, eq, or pattern matching as above.  (If
  1229.      you're curious as to whether the optimizer has done this for
  1230.      a particular case statement, you can use the -D1024 switch
  1231.      to list the syntax tree before execution.)
  1232.  
  1233.      SSiimmppllee ssttaatteemmeennttss
  1234.  
  1235.      The only kind of simple statement is an expression evaluated
  1236.      for its side effects.  Every expression (simple statement)
  1237.      must be terminated with a semicolon.  Note that this is like
  1238.      C, but unlike Pascal (and _a_w_k).
  1239.  
  1240.      Any simple statement may optionally be followed by a single
  1241.      modifier, just before the terminating semicolon.  The possi-
  1242.      ble modifiers are:
  1243.  
  1244.           if EXPR
  1245.           unless EXPR
  1246.           while EXPR
  1247.           until EXPR
  1248.  
  1249.  
  1250.  
  1251. Sprite v1.0                                                    19
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. PERL                      User Commands                      PERL
  1259.  
  1260.  
  1261.  
  1262.      The _i_f and _u_n_l_e_s_s modifiers have the expected semantics.
  1263.      The _w_h_i_l_e and _u_n_t_i_l modifiers also have the expected seman-
  1264.      tics (conditional evaluated first), except when applied to a
  1265.      do-BLOCK or a do-SUBROUTINE command, in which case the block
  1266.      executes once before the conditional is evaluated.  This is
  1267.      so that you can write loops like:
  1268.  
  1269.           do {
  1270.                $_ = <STDIN>;
  1271.                ...
  1272.           } until $_ eq ".\n";
  1273.  
  1274.      (See the _d_o operator below.  Note also that the loop control
  1275.      commands described later will NOT work in this construct,
  1276.      since modifiers don't take loop labels.  Sorry.)
  1277.  
  1278.      EExxpprreessssiioonnss
  1279.  
  1280.      Since _p_e_r_l expressions work almost exactly like C expres-
  1281.      sions, only the differences will be mentioned here.
  1282.  
  1283.      Here's what _p_e_r_l has that C doesn't:
  1284.  
  1285.      **      The exponentiation operator.
  1286.  
  1287.      **=     The exponentiation assignment operator.
  1288.  
  1289.      ()      The null list, used to initialize an array to null.
  1290.  
  1291.      .       Concatenation of two strings.
  1292.  
  1293.      .=      The concatenation assignment operator.
  1294.  
  1295.      eq      String equality (== is numeric equality).  For a
  1296.              mnemonic just think of "eq" as a string.  (If you
  1297.              are used to the _a_w_k behavior of using == for either
  1298.              string or numeric equality based on the current form
  1299.              of the comparands, beware!  You must be explicit
  1300.              here.)
  1301.  
  1302.      ne      String inequality (!= is numeric inequality).
  1303.  
  1304.      lt      String less than.
  1305.  
  1306.      gt      String greater than.
  1307.  
  1308.      le      String less than or equal.
  1309.  
  1310.      ge      String greater than or equal.
  1311.  
  1312.      cmp     String comparison, returning -1, 0, or 1.
  1313.  
  1314.  
  1315.  
  1316.  
  1317. Sprite v1.0                                                    20
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324. PERL                      User Commands                      PERL
  1325.  
  1326.  
  1327.  
  1328.      <=>     Numeric comparison, returning -1, 0, or 1.
  1329.  
  1330.      =~      Certain operations search or modify the string "$_"
  1331.              by default.  This operator makes that kind of opera-
  1332.              tion work on some other string.  The right argument
  1333.              is a search pattern, substitution, or translation.
  1334.              The left argument is what is supposed to be
  1335.              searched, substituted, or translated instead of the
  1336.              default "$_".  The return value indicates the suc-
  1337.              cess of the operation.  (If the right argument is an
  1338.              expression other than a search pattern, substitu-
  1339.              tion, or translation, it is interpreted as a search
  1340.              pattern at run time.  This is less efficient than an
  1341.              explicit search, since the pattern must be compiled
  1342.              every time the expression is evaluated.) The pre-
  1343.              cedence of this operator is lower than unary minus
  1344.              and autoincrement/decrement, but higher than every-
  1345.              thing else.
  1346.  
  1347.      !~      Just like =~ except the return value is negated.
  1348.  
  1349.      x       The repetition operator.  Returns a string consist-
  1350.              ing of the left operand repeated the number of times
  1351.              specified by the right operand.  In an array con-
  1352.              text, if the left operand is a list in parens, it
  1353.              repeats the list.
  1354.  
  1355.                   print '-' x 80;          # print row of dashes
  1356.                   print '-' x80;      # illegal, x80 is identifier
  1357.  
  1358.                   print "\t" x ($tab/8), ' ' x ($tab%8);  # tab over
  1359.  
  1360.                   @ones = (1) x 80;        # an array of 80 1's
  1361.                   @ones = (5) x @ones;          # set all elements to 5
  1362.  
  1363.  
  1364.      x=      The repetition assignment operator.  Only works on
  1365.              scalars.
  1366.  
  1367.      ..      The range operator, which is really two different
  1368.              operators depending on the context.  In an array
  1369.              context, returns an array of values counting (by
  1370.              ones) from the left value to the right value.  This
  1371.              is useful for writing "for (1..10)" loops and for
  1372.              doing slice operations on arrays.
  1373.  
  1374.              In a scalar context, .. returns a boolean value.
  1375.              The operator is bistable, like a flip-flop..  Each
  1376.              .. operator maintains its own boolean state.  It is
  1377.              false as long as its left operand is false.  Once
  1378.              the left operand is true, the range operator stays
  1379.              true until the right operand is true, AFTER which
  1380.  
  1381.  
  1382.  
  1383. Sprite v1.0                                                    21
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390. PERL                      User Commands                      PERL
  1391.  
  1392.  
  1393.  
  1394.              the range operator becomes false again.  (It doesn't
  1395.              become false till the next time the range operator
  1396.              is evaluated.  It can become false on the same
  1397.              evaluation it became true, but it still returns true
  1398.              once.) The right operand is not evaluated while the
  1399.              operator is in the "false" state, and the left
  1400.              operand is not evaluated while the operator is in
  1401.              the "true" state.  The scalar .. operator is pri-
  1402.              marily intended for doing line number ranges after
  1403.              the fashion of _s_e_d or _a_w_k.  The precedence is a lit-
  1404.              tle lower than || and &&.  The value returned is
  1405.              either the null string for false, or a sequence
  1406.              number (beginning with 1) for true.  The sequence
  1407.              number is reset for each range encountered.  The
  1408.              final sequence number in a range has the string 'E0'
  1409.              appended to it, which doesn't affect its numeric
  1410.              value, but gives you something to search for if you
  1411.              want to exclude the endpoint.  You can exclude the
  1412.              beginning point by waiting for the sequence number
  1413.              to be greater than 1.  If either operand of scalar
  1414.              .. is static, that operand is implicitly compared to
  1415.              the $. variable, the current line number.  Examples:
  1416.  
  1417.              As a scalar operator:
  1418.                  if (101 .. 200) { print; }     # print 2nd hundred lines
  1419.  
  1420.                  next line if (1 .. /^$/); # skip header lines
  1421.  
  1422.                  s/^/> / if (/^$/ .. eof());    # quote body
  1423.  
  1424.              As an array operator:
  1425.                  for (101 .. 200) { print; }    # print $_ 100 times
  1426.  
  1427.                  @foo = @foo[$[ .. $#foo]; # an expensive no-op
  1428.                  @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
  1429.  
  1430.  
  1431.      -x      A file test.  This unary operator takes one argu-
  1432.              ment, either a filename or a filehandle, and tests
  1433.              the associated file to see if something is true
  1434.              about it.  If the argument is omitted, tests $_,
  1435.              except for -t, which tests _S_T_D_I_N.  It returns 1 for
  1436.              true and '' for false, or the undefined value if the
  1437.              file doesn't exist.  Precedence is higher than logi-
  1438.              cal and relational operators, but lower than arith-
  1439.              metic operators.  The operator may be any of:
  1440.                   -r   File is readable by effective uid.
  1441.                   -w   File is writable by effective uid.
  1442.                   -x   File is executable by effective uid.
  1443.                   -o   File is owned by effective uid.
  1444.                   -R   File is readable by real uid.
  1445.                   -W   File is writable by real uid.
  1446.  
  1447.  
  1448.  
  1449. Sprite v1.0                                                    22
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456. PERL                      User Commands                      PERL
  1457.  
  1458.  
  1459.  
  1460.                   -X   File is executable by real uid.
  1461.                   -O   File is owned by real uid.
  1462.                   -e   File exists.
  1463.                   -z   File has zero size.
  1464.                   -s   File has non-zero size (returns size).
  1465.                   -f   File is a plain file.
  1466.                   -d   File is a directory.
  1467.                   -l   File is a symbolic link.
  1468.                   -p   File is a named pipe (FIFO).
  1469.                   -S   File is a socket.
  1470.                   -b   File is a block special file.
  1471.                   -c   File is a character special file.
  1472.                   -u   File has setuid bit set.
  1473.                   -g   File has setgid bit set.
  1474.                   -k   File has sticky bit set.
  1475.                   -t   Filehandle is opened to a tty.
  1476.                   -T   File is a text file.
  1477.                   -B   File is a binary file (opposite of -T).
  1478.                   -M   Age of file in days when script started.
  1479.                   -A   Same for access time.
  1480.                   -C   Same for inode change time.
  1481.  
  1482.              The interpretation of the file permission operators
  1483.              -r, -R, -w, -W, -x and -X is based solely on the
  1484.              mode of the file and the uids and gids of the user.
  1485.              There may be other reasons you can't actually read,
  1486.              write or execute the file.  Also note that, for the
  1487.              superuser, -r, -R, -w and -W always return 1, and -x
  1488.              and -X return 1 if any execute bit is set in the
  1489.              mode.  Scripts run by the superuser may thus need to
  1490.              do a stat() in order to determine the actual mode of
  1491.              the file, or temporarily set the uid to something
  1492.              else.
  1493.  
  1494.              Example:
  1495.  
  1496.                   while (<>) {
  1497.                        chop;
  1498.                        next unless -f $_;  # ignore specials
  1499.                        ...
  1500.                   }
  1501.  
  1502.              Note that -s/a/b/ does not do a negated substitu-
  1503.              tion.  Saying -exp($foo) still works as expected,
  1504.              however--only single letters following a minus are
  1505.              interpreted as file tests.
  1506.  
  1507.              The -T and -B switches work as follows.  The first
  1508.              block or so of the file is examined for odd charac-
  1509.              ters such as strange control codes or metacharac-
  1510.              ters.  If too many odd characters (>10%) are found,
  1511.              it's a -B file, otherwise it's a -T file.  Also, any
  1512.  
  1513.  
  1514.  
  1515. Sprite v1.0                                                    23
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522. PERL                      User Commands                      PERL
  1523.  
  1524.  
  1525.  
  1526.              file containing null in the first block is con-
  1527.              sidered a binary file.  If -T or -B is used on a
  1528.              filehandle, the current stdio buffer is examined
  1529.              rather than the first block.  Both -T and -B return
  1530.              TRUE on a null file, or a file at EOF when testing a
  1531.              filehandle.
  1532.  
  1533.      If any of the file tests (or either stat operator) are given
  1534.      the special filehandle consisting of a solitary underline,
  1535.      then the stat structure of the previous file test (or stat
  1536.      operator) is used, saving a system call.  (This doesn't work
  1537.      with -t, and you need to remember that lstat and -l will
  1538.      leave values in the stat structure for the symbolic link,
  1539.      not the real file.) Example:
  1540.  
  1541.           print "Can do.\n" if -r $a || -w _ || -x _;
  1542.  
  1543.           stat($filename);
  1544.           print "Readable\n" if -r _;
  1545.           print "Writable\n" if -w _;
  1546.           print "Executable\n" if -x _;
  1547.           print "Setuid\n" if -u _;
  1548.           print "Setgid\n" if -g _;
  1549.           print "Sticky\n" if -k _;
  1550.           print "Text\n" if -T _;
  1551.           print "Binary\n" if -B _;
  1552.  
  1553.  
  1554.      Here is what C has that _p_e_r_l doesn't:
  1555.  
  1556.      unary &     Address-of operator.
  1557.  
  1558.      unary *     Dereference-address operator.
  1559.  
  1560.      (TYPE)      Type casting operator.
  1561.  
  1562.      Like C, _p_e_r_l does a certain amount of expression evaluation
  1563.      at compile time, whenever it determines that all of the
  1564.      arguments to an operator are static and have no side
  1565.      effects.  In particular, string concatenation happens at
  1566.      compile time between literals that don't do variable substi-
  1567.      tution.  Backslash interpretation also happens at compile
  1568.      time.  You can say
  1569.  
  1570.           'Now is the time for all' . "\n" .
  1571.           'good men to come to.'
  1572.  
  1573.      and this all reduces to one string internally.
  1574.  
  1575.      The autoincrement operator has a little extra built-in magic
  1576.      to it.  If you increment a variable that is numeric, or that
  1577.      has ever been used in a numeric context, you get a normal
  1578.  
  1579.  
  1580.  
  1581. Sprite v1.0                                                    24
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588. PERL                      User Commands                      PERL
  1589.  
  1590.  
  1591.  
  1592.      increment.  If, however, the variable has only been used in
  1593.      string contexts since it was set, and has a value that is
  1594.      not null and matches the pattern /^[a-zA-Z]*[0-9]*$/, the
  1595.      increment is done as a string, preserving each character
  1596.      within its range, with carry:
  1597.  
  1598.           print ++($foo = '99');   # prints '100'
  1599.           print ++($foo = 'a0');   # prints 'a1'
  1600.           print ++($foo = 'Az');   # prints 'Ba'
  1601.           print ++($foo = 'zz');   # prints 'aaa'
  1602.  
  1603.      The autodecrement is not magical.
  1604.  
  1605.      The range operator (in an array context) makes use of the
  1606.      magical autoincrement algorithm if the minimum and maximum
  1607.      are strings.  You can say
  1608.  
  1609.           @alphabet = ('A' .. 'Z');
  1610.  
  1611.      to get all the letters of the alphabet, or
  1612.  
  1613.           $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  1614.  
  1615.      to get a hexadecimal digit, or
  1616.  
  1617.           @z2 = ('01' .. '31');  print @z2[$mday];
  1618.  
  1619.      to get dates with leading zeros.  (If the final value speci-
  1620.      fied is not in the sequence that the magical increment would
  1621.      produce, the sequence goes until the next value would be
  1622.      longer than the final value specified.)
  1623.  
  1624.      The || and && operators differ from C's in that, rather than
  1625.      returning 0 or 1, they return the last value evaluated.
  1626.      Thus, a portable way to find out the home directory might
  1627.      be:
  1628.  
  1629.           $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  1630.               (getpwuid($<))[7] || die "You're homeless!\n";
  1631.  
  1632.  
  1633.      Along with the literals and variables mentioned earlier, the
  1634.      operations in the following section can serve as terms in an
  1635.      expression.  Some of these operations take a LIST as an
  1636.      argument.  Such a list can consist of any combination of
  1637.      scalar arguments or array values; the array values will be
  1638.      included in the list as if each individual element were
  1639.      interpolated at that point in the list, forming a longer
  1640.      single-dimensional array value.  Elements of the LIST should
  1641.      be separated by commas.  If an operation is listed both with
  1642.      and without parentheses around its arguments, it means you
  1643.      can either use it as a unary operator or as a function call.
  1644.  
  1645.  
  1646.  
  1647. Sprite v1.0                                                    25
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654. PERL                      User Commands                      PERL
  1655.  
  1656.  
  1657.  
  1658.      To use it as a function call, the next token on the same
  1659.      line must be a left parenthesis.  (There may be intervening
  1660.      white space.) Such a function then has highest precedence,
  1661.      as you would expect from a function.  If any token other
  1662.      than a left parenthesis follows, then it is a unary opera-
  1663.      tor, with a precedence depending only on whether it is a
  1664.      LIST operator or not.  LIST operators have lowest pre-
  1665.      cedence.  All other unary operators have a precedence
  1666.      greater than relational operators but less than arithmetic
  1667.      operators.  See the section on Precedence.
  1668.  
  1669.      /PATTERN/
  1670.              See m/PATTERN/.
  1671.  
  1672.      ?PATTERN?
  1673.              This is just like the /pattern/ search, except that
  1674.              it matches only once between calls to the _r_e_s_e_t
  1675.              operator.  This is a useful optimization when you
  1676.              only want to see the first occurrence of something
  1677.              in each file of a set of files, for instance.  Only
  1678.              ?? patterns local to the current package are reset.
  1679.  
  1680.      accept(NEWSOCKET,GENERICSOCKET)
  1681.              Does the same thing that the accept system call
  1682.              does.  Returns true if it succeeded, false other-
  1683.              wise.  See example in section on Interprocess Com-
  1684.              munication.
  1685.  
  1686.      alarm(SECONDS)
  1687.  
  1688.      alarm SECONDS
  1689.              Arranges to have a SIGALRM delivered to this process
  1690.              after the specified number of seconds (minus 1,
  1691.              actually) have elapsed.  Thus, alarm(15) will cause
  1692.              a SIGALRM at some point more than 14 seconds in the
  1693.              future.  Only one timer may be counting at once.
  1694.              Each call disables the previous timer, and an argu-
  1695.              ment of 0 may be supplied to cancel the previous
  1696.              timer without starting a new one.  The returned
  1697.              value is the amount of time remaining on the previ-
  1698.              ous timer.
  1699.  
  1700.      atan2(Y,X)
  1701.              Returns the arctangent of Y/X in the range -PI to
  1702.              PI.
  1703.  
  1704.      bind(SOCKET,NAME)
  1705.              Does the same thing that the bind system call does.
  1706.              Returns true if it succeeded, false otherwise.  NAME
  1707.              should be a packed address of the proper type for
  1708.              the socket.  See example in section on Interprocess
  1709.              Communication.
  1710.  
  1711.  
  1712.  
  1713. Sprite v1.0                                                    26
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720. PERL                      User Commands                      PERL
  1721.  
  1722.  
  1723.  
  1724.      binmode(FILEHANDLE)
  1725.  
  1726.      binmode FILEHANDLE
  1727.              Arranges for the file to be read in "binary" mode in
  1728.              operating systems that distinguish between binary
  1729.              and text files.  Files that are not read in binary
  1730.              mode have CR LF sequences translated to LF on input
  1731.              and LF translated to CR LF on output.  Binmode has
  1732.              no effect under Unix.  If FILEHANDLE is an expres-
  1733.              sion, the value is taken as the name of the filehan-
  1734.              dle.
  1735.  
  1736.      caller(EXPR)
  1737.  
  1738.      caller  Returns the context of the current subroutine call:
  1739.  
  1740.                   ($package,$filename,$line) = caller;
  1741.  
  1742.              With EXPR, returns some extra information that the
  1743.              debugger uses to print a stack trace.  The value of
  1744.              EXPR indicates how many call frames to go back
  1745.              before the current one.
  1746.  
  1747.      chdir(EXPR)
  1748.  
  1749.      chdir EXPR
  1750.              Changes the working directory to EXPR, if possible.
  1751.              If EXPR is omitted, changes to home directory.
  1752.              Returns 1 upon success, 0 otherwise.  See example
  1753.              under _d_i_e.
  1754.  
  1755.      chmod(LIST)
  1756.  
  1757.      chmod LIST
  1758.              Changes the permissions of a list of files.  The
  1759.              first element of the list must be the numerical
  1760.              mode.  Returns the number of files successfully
  1761.              changed.
  1762.  
  1763.                   $cnt = chmod 0755, 'foo', 'bar';
  1764.                   chmod 0755, @executables;
  1765.  
  1766.  
  1767.      chop(LIST)
  1768.  
  1769.      chop(VARIABLE)
  1770.  
  1771.      chop VARIABLE
  1772.  
  1773.      chop    Chops off the last character of a string and returns
  1774.              the character chopped.  It's used primarily to
  1775.              remove the newline from the end of an input record,
  1776.  
  1777.  
  1778.  
  1779. Sprite v1.0                                                    27
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786. PERL                      User Commands                      PERL
  1787.  
  1788.  
  1789.  
  1790.              but is much more efficient than s/\n// because it
  1791.              neither scans nor copies the string.  If VARIABLE is
  1792.              omitted, chops $_.  Example:
  1793.  
  1794.                   while (<>) {
  1795.                        chop;     # avoid \n on last field
  1796.                        @array = split(/:/);
  1797.                        ...
  1798.                   }
  1799.  
  1800.              You can actually chop anything that's an lvalue,
  1801.              including an assignment:
  1802.  
  1803.                   chop($cwd = `pwd`);
  1804.                   chop($answer = <STDIN>);
  1805.  
  1806.              If you chop a list, each element is chopped.  Only
  1807.              the value of the last chop is returned.
  1808.  
  1809.      chown(LIST)
  1810.  
  1811.      chown LIST
  1812.              Changes the owner (and group) of a list of files.
  1813.              The first two elements of the list must be the
  1814.              NUMERICAL uid and gid, in that order.  Returns the
  1815.              number of files successfully changed.
  1816.  
  1817.                   $cnt = chown $uid, $gid, 'foo', 'bar';
  1818.                   chown $uid, $gid, @filenames;
  1819.  
  1820.  
  1821.  
  1822.  
  1823.  
  1824.  
  1825.  
  1826.  
  1827.  
  1828.  
  1829.  
  1830.  
  1831.  
  1832.  
  1833.  
  1834.  
  1835.  
  1836.  
  1837.  
  1838.  
  1839.  
  1840.  
  1841.  
  1842.  
  1843.  
  1844.  
  1845. Sprite v1.0                                                    28
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852. PERL                      User Commands                      PERL
  1853.  
  1854.  
  1855.  
  1856.              Here's an example that looks up non-numeric uids in
  1857.              the passwd file:
  1858.  
  1859.                   print "User: ";
  1860.                   $user = <STDIN>;
  1861.                   chop($user);
  1862.                   print "Files: "
  1863.                   $pattern = <STDIN>;
  1864.                   chop($pattern);
  1865.                   open(pass, '/etc/passwd')
  1866.                        || die "Can't open passwd: $!\n";
  1867.                   while (<pass>) {
  1868.                        ($login,$pass,$uid,$gid) = split(/:/);
  1869.                        $uid{$login} = $uid;
  1870.                        $gid{$login} = $gid;
  1871.                   }
  1872.                   @ary = <${pattern}>;     # get filenames
  1873.                   if ($uid{$user} eq '') {
  1874.                        die "$user not in passwd file";
  1875.                   }
  1876.                   else {
  1877.                        chown $uid{$user}, $gid{$user}, @ary;
  1878.                   }
  1879.  
  1880.  
  1881.      chroot(FILENAME)
  1882.  
  1883.      chroot FILENAME
  1884.              Does the same as the system call of that name.  If
  1885.              you don't know what it does, don't worry about it.
  1886.              If FILENAME is omitted, does chroot to $_.
  1887.  
  1888.      close(FILEHANDLE)
  1889.  
  1890.      close FILEHANDLE
  1891.              Closes the file or pipe associated with the file
  1892.              handle.  You don't have to close FILEHANDLE if you
  1893.              are immediately going to do another open on it,
  1894.              since open will close it for you.  (See _o_p_e_n.) How-
  1895.              ever, an explicit close on an input file resets the
  1896.              line counter ($.), while the implicit close done by
  1897.              _o_p_e_n does not.  Also, closing a pipe will wait for
  1898.              the process executing on the pipe to complete, in
  1899.              case you want to look at the output of the pipe
  1900.              afterwards.  Closing a pipe explicitly also puts the
  1901.              status value of the command into $?.  Example:
  1902.  
  1903.                   open(OUTPUT, '|sort >foo');   # pipe to sort
  1904.                   ...  # print stuff to output
  1905.                   close OUTPUT;       # wait for sort to finish
  1906.                   open(INPUT, 'foo'); # get sort's results
  1907.  
  1908.  
  1909.  
  1910.  
  1911. Sprite v1.0                                                    29
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918. PERL                      User Commands                      PERL
  1919.  
  1920.  
  1921.  
  1922.              FILEHANDLE may be an expression whose value gives
  1923.              the real filehandle name.
  1924.  
  1925.      closedir(DIRHANDLE)
  1926.  
  1927.      closedir DIRHANDLE
  1928.              Closes a directory opened by opendir().
  1929.  
  1930.      connect(SOCKET,NAME)
  1931.              Does the same thing that the connect system call
  1932.              does.  Returns true if it succeeded, false other-
  1933.              wise.  NAME should be a package address of the
  1934.              proper type for the socket.  See example in section
  1935.              on Interprocess Communication.
  1936.  
  1937.      cos(EXPR)
  1938.  
  1939.      cos EXPR
  1940.              Returns the cosine of EXPR (expressed in radians).
  1941.              If EXPR is omitted takes cosine of $_.
  1942.  
  1943.      crypt(PLAINTEXT,SALT)
  1944.              Encrypts a string exactly like the crypt() function
  1945.              in the C library.  Useful for checking the password
  1946.              file for lousy passwords.  Only the guys wearing
  1947.              white hats should do this.
  1948.  
  1949.      dbmclose(ASSOC_ARRAY)
  1950.  
  1951.      dbmclose ASSOC_ARRAY
  1952.              Breaks the binding between a dbm file and an associ-
  1953.              ative array.  The values remaining in the associa-
  1954.              tive array are meaningless unless you happen to want
  1955.              to know what was in the cache for the dbm file.
  1956.              This function is only useful if you have ndbm.
  1957.  
  1958.      dbmopen(ASSOC,DBNAME,MODE)
  1959.              This binds a dbm or ndbm file to an associative
  1960.              array.  ASSOC is the name of the associative array.
  1961.              (Unlike normal open, the first argument is NOT a
  1962.              filehandle, even though it looks like one).  DBNAME
  1963.              is the name of the database (without the .dir or
  1964.              .pag extension).  If the database does not exist, it
  1965.              is created with protection specified by MODE (as
  1966.              modified by the umask).  If your system only sup-
  1967.              ports the older dbm functions, you may perform only
  1968.              one dbmopen in your program.  If your system has
  1969.              neither dbm nor ndbm, calling dbmopen produces a
  1970.              fatal error.
  1971.  
  1972.              Values assigned to the associative array prior to
  1973.              the dbmopen are lost.  A certain number of values
  1974.  
  1975.  
  1976.  
  1977. Sprite v1.0                                                    30
  1978.  
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984. PERL                      User Commands                      PERL
  1985.  
  1986.  
  1987.  
  1988.              from the dbm file are cached in memory.  By default
  1989.              this number is 64, but you can increase it by preal-
  1990.              locating that number of garbage entries in the asso-
  1991.              ciative array before the dbmopen.  You can flush the
  1992.              cache if necessary with the reset command.
  1993.  
  1994.              If you don't have write access to the dbm file, you
  1995.              can only read associative array variables, not set
  1996.              them.  If you want to test whether you can write,
  1997.              either use file tests or try setting a dummy array
  1998.              entry inside an eval, which will trap the error.
  1999.  
  2000.              Note that functions such as keys() and values() may
  2001.              return huge array values when used on large dbm
  2002.              files.  You may prefer to use the each() function to
  2003.              iterate over large dbm files.  Example:
  2004.  
  2005.                   # print out history file offsets
  2006.                   dbmopen(HIST,'/usr/lib/news/history',0666);
  2007.                   while (($key,$val) = each %HIST) {
  2008.                        print $key, ' = ', unpack('L',$val), "\n";
  2009.                   }
  2010.                   dbmclose(HIST);
  2011.  
  2012.  
  2013.      defined(EXPR)
  2014.  
  2015.      defined EXPR
  2016.              Returns a boolean value saying whether the lvalue
  2017.              EXPR has a real value or not.  Many operations
  2018.              return the undefined value under exceptional condi-
  2019.              tions, such as end of file, uninitialized variable,
  2020.              system error and such.  This function allows you to
  2021.              distinguish between an undefined null string and a
  2022.              defined null string with operations that might
  2023.              return a real null string, in particular referencing
  2024.              elements of an array.  You may also check to see if
  2025.              arrays or subroutines exist.  Use on predefined
  2026.              variables is not guaranteed to produce intuitive
  2027.              results.  Examples:
  2028.  
  2029.                   print if defined $switch{'D'};
  2030.                   print "$val\n" while defined($val = pop(@ary));
  2031.                   die "Can't readlink $sym: $!"
  2032.                        unless defined($value = readlink $sym);
  2033.                   eval '@foo = ()' if defined(@foo);
  2034.                   die "No XYZ package defined" unless defined %_XYZ;
  2035.                   sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
  2036.  
  2037.              See also undef.
  2038.  
  2039.  
  2040.  
  2041.  
  2042.  
  2043. Sprite v1.0                                                    31
  2044.  
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050. PERL                      User Commands                      PERL
  2051.  
  2052.  
  2053.  
  2054.      delete $ASSOC{KEY}
  2055.              Deletes the specified value from the specified asso-
  2056.              ciative array.  Returns the deleted value, or the
  2057.              undefined value if nothing was deleted.  Deleting
  2058.              from $ENV{} modifies the environment.  Deleting from
  2059.              an array bound to a dbm file deletes the entry from
  2060.              the dbm file.
  2061.  
  2062.              The following deletes all the values of an associa-
  2063.              tive array:
  2064.  
  2065.                   foreach $key (keys %ARRAY) {
  2066.                        delete $ARRAY{$key};
  2067.                   }
  2068.  
  2069.              (But it would be faster to use the _r_e_s_e_t command.
  2070.              Saying undef %ARRAY is faster yet.)
  2071.  
  2072.      die(LIST)
  2073.  
  2074.      die LIST
  2075.              Outside of an eval, prints the value of LIST to
  2076.              _S_T_D_E_R_R and exits with the current value of $!
  2077.              (errno).  If $! is 0, exits with the value of ($? >>
  2078.              8) (`command` status).  If ($? >> 8) is 0, exits
  2079.              with 255.  Inside an eval, the error message is
  2080.              stuffed into $@ and the eval is terminated with the
  2081.              undefined value.
  2082.  
  2083.              Equivalent examples:
  2084.  
  2085.                   die "Can't cd to spool: $!\n"
  2086.                        unless chdir '/usr/spool/news';
  2087.  
  2088.                   chdir '/usr/spool/news' || die "Can't cd to spool: $!\n"
  2089.  
  2090.  
  2091.              If the value of EXPR does not end in a newline, the
  2092.              current script line number and input line number (if
  2093.              any) are also printed, and a newline is supplied.
  2094.              Hint: sometimes appending ", stopped" to your mes-
  2095.              sage will cause it to make better sense when the
  2096.              string "at foo line 123" is appended.  Suppose you
  2097.              are running script "canasta".
  2098.  
  2099.                   die "/etc/games is no good";
  2100.                   die "/etc/games is no good, stopped";
  2101.  
  2102.              produce, respectively
  2103.  
  2104.                   /etc/games is no good at canasta line 123.
  2105.                   /etc/games is no good, stopped at canasta line 123.
  2106.  
  2107.  
  2108.  
  2109. Sprite v1.0                                                    32
  2110.  
  2111.  
  2112.  
  2113.  
  2114.  
  2115.  
  2116. PERL                      User Commands                      PERL
  2117.  
  2118.  
  2119.  
  2120.              See also _e_x_i_t.
  2121.  
  2122.      do BLOCK
  2123.              Returns the value of the last command in the
  2124.              sequence of commands indicated by BLOCK.  When modi-
  2125.              fied by a loop modifier, executes the BLOCK once
  2126.              before testing the loop condition.  (On other state-
  2127.              ments the loop modifiers test the conditional
  2128.              first.)
  2129.  
  2130.      do SUBROUTINE (LIST)
  2131.              Executes a SUBROUTINE declared by a _s_u_b declaration,
  2132.              and returns the value of the last expression
  2133.              evaluated in SUBROUTINE.  If there is no subroutine
  2134.              by that name, produces a fatal error.  (You may use
  2135.              the "defined" operator to determine if a subroutine
  2136.              exists.) If you pass arrays as part of LIST you may
  2137.              wish to pass the length of the array in front of
  2138.              each array.  (See the section on subroutines later
  2139.              on.) The parentheses are required to avoid confusion
  2140.              with the "do EXPR" form.
  2141.  
  2142.              SUBROUTINE may also be a single scalar variable, in
  2143.              which case the name of the subroutine to execute is
  2144.              taken from the variable.
  2145.  
  2146.              As an alternate (and preferred) form, you may call a
  2147.              subroutine by prefixing the name with an ampersand:
  2148.              &foo(@args).  If you aren't passing any arguments,
  2149.              you don't have to use parentheses.  If you omit the
  2150.              parentheses, no @_ array is passed to the subrou-
  2151.              tine.  The & form is also used to specify subrou-
  2152.              tines to the defined and undef operators:
  2153.  
  2154.                   if (defined &$var) { &$var($parm); undef &$var; }
  2155.  
  2156.  
  2157.      do EXPR Uses the value of EXPR as a filename and executes
  2158.              the contents of the file as a _p_e_r_l script.  Its pri-
  2159.              mary use is to include subroutines from a _p_e_r_l sub-
  2160.              routine library.
  2161.  
  2162.                   do 'stat.pl';
  2163.  
  2164.              is just like
  2165.  
  2166.                   eval `cat stat.pl`;
  2167.  
  2168.              except that it's more efficient, more concise, keeps
  2169.              track of the current filename for error messages,
  2170.              and searches all the --II libraries if the file isn't
  2171.              in the current directory (see also the @INC array in
  2172.  
  2173.  
  2174.  
  2175. Sprite v1.0                                                    33
  2176.  
  2177.  
  2178.  
  2179.  
  2180.  
  2181.  
  2182. PERL                      User Commands                      PERL
  2183.  
  2184.  
  2185.  
  2186.              Predefined Names).  It's the same, however, in that
  2187.              it does reparse the file every time you call it, so
  2188.              if you are going to use the file inside a loop you
  2189.              might prefer to use -P and #include, at the expense
  2190.              of a little more startup time.  (The main problem
  2191.              with #include is that cpp doesn't grok # comments--a
  2192.              workaround is to use ";#" for standalone comments.)
  2193.              Note that the following are NOT equivalent:
  2194.  
  2195.                   do $foo;  # eval a file
  2196.                   do $foo();     # call a subroutine
  2197.  
  2198.              Note that inclusion of library routines is better
  2199.              done with the "require" operator.
  2200.  
  2201.      dump LABEL
  2202.              This causes an immediate core dump.  Primarily this
  2203.              is so that you can use the undump program to turn
  2204.              your core dump into an executable binary after hav-
  2205.              ing initialized all your variables at the beginning
  2206.              of the program.  When the new binary is executed it
  2207.              will begin by executing a "goto LABEL" (with all the
  2208.              restrictions that goto suffers).  Think of it as a
  2209.              goto with an intervening core dump and reincarna-
  2210.              tion.  If LABEL is omitted, restarts the program
  2211.              from the top.  WARNING: any files opened at the time
  2212.              of the dump will NOT be open any more when the pro-
  2213.              gram is reincarnated, with possible resulting confu-
  2214.              sion on the part of perl.  See also -u.
  2215.  
  2216.              Example:
  2217.  
  2218.                   #!/usr/bin/perl
  2219.                   require 'getopt.pl';
  2220.                   require 'stat.pl';
  2221.                   %days = (
  2222.                       'Sun',1,
  2223.                       'Mon',2,
  2224.                       'Tue',3,
  2225.                       'Wed',4,
  2226.                       'Thu',5,
  2227.                       'Fri',6,
  2228.                       'Sat',7);
  2229.  
  2230.                   dump QUICKSTART if $ARGV[0] eq '-d';
  2231.  
  2232.                  QUICKSTART:
  2233.                   do Getopt('f');
  2234.  
  2235.  
  2236.  
  2237.  
  2238.  
  2239.  
  2240.  
  2241. Sprite v1.0                                                    34
  2242.  
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248. PERL                      User Commands                      PERL
  2249.  
  2250.  
  2251.  
  2252.      each(ASSOC_ARRAY)
  2253.  
  2254.      each ASSOC_ARRAY
  2255.              Returns a 2 element array consisting of the key and
  2256.              value for the next value of an associative array, so
  2257.              that you can iterate over it.  Entries are returned
  2258.              in an apparently random order.  When the array is
  2259.              entirely read, a null array is returned (which when
  2260.              assigned produces a FALSE (0) value).  The next call
  2261.              to each() after that will start iterating again.
  2262.              The iterator can be reset only by reading all the
  2263.              elements from the array.  You must not modify the
  2264.              array while iterating over it.  There is a single
  2265.              iterator for each associative array, shared by all
  2266.              each(), keys() and values() function calls in the
  2267.              program.  The following prints out your environment
  2268.              like the printenv program, only in a different
  2269.              order:
  2270.  
  2271.                   while (($key,$value) = each %ENV) {
  2272.                        print "$key=$value\n";
  2273.                   }
  2274.  
  2275.              See also keys() and values().
  2276.  
  2277.      eof(FILEHANDLE)
  2278.  
  2279.      eof()
  2280.  
  2281.      eof     Returns 1 if the next read on FILEHANDLE will return
  2282.              end of file, or if FILEHANDLE is not open.  FILEHAN-
  2283.              DLE may be an expression whose value gives the real
  2284.              filehandle name.  (Note that this function actually
  2285.              reads a character and then ungetc's it, so it is not
  2286.              very useful in an interactive context.) An eof
  2287.              without an argument returns the eof status for the
  2288.              last file read.  Empty parentheses () may be used to
  2289.              indicate the pseudo file formed of the files listed
  2290.              on the command line, i.e. eof() is reasonable to use
  2291.              inside a while (<>) loop to detect the end of only
  2292.              the last file.  Use eof(ARGV) or eof without the
  2293.              parentheses to test EACH file in a while (<>) loop.
  2294.              Examples:
  2295.  
  2296.                   # insert dashes just before last line of last file
  2297.                   while (<>) {
  2298.                        if (eof()) {
  2299.                             print "--------------\n";
  2300.                        }
  2301.                        print;
  2302.                   }
  2303.  
  2304.  
  2305.  
  2306.  
  2307. Sprite v1.0                                                    35
  2308.  
  2309.  
  2310.  
  2311.  
  2312.  
  2313.  
  2314. PERL                      User Commands                      PERL
  2315.  
  2316.  
  2317.  
  2318.                   # reset line numbering on each input file
  2319.                   while (<>) {
  2320.                        print "$.\t$_";
  2321.                        if (eof) {     # Not eof().
  2322.                             close(ARGV);
  2323.                        }
  2324.                   }
  2325.  
  2326.  
  2327.      eval(EXPR)
  2328.  
  2329.      eval EXPR
  2330.  
  2331.      eval BLOCK
  2332.              EXPR is parsed and executed as if it were a little
  2333.              _p_e_r_l program.  It is executed in the context of the
  2334.              current _p_e_r_l program, so that any variable settings,
  2335.              subroutine or format definitions remain afterwards.
  2336.              The value returned is the value of the last expres-
  2337.              sion evaluated, just as with subroutines.  If there
  2338.              is a syntax error or runtime error, or a die state-
  2339.              ment is executed, an undefined value is returned by
  2340.              eval, and $@ is set to the error message.  If there
  2341.              was no error, $@ is guaranteed to be a null string.
  2342.              If EXPR is omitted, evaluates $_.  The final semi-
  2343.              colon, if any, may be omitted from the expression.
  2344.  
  2345.              Note that, since eval traps otherwise-fatal errors,
  2346.              it is useful for determining whether a particular
  2347.              feature (such as dbmopen or symlink) is implemented.
  2348.              It is also Perl's exception trapping mechanism,
  2349.              where the die operator is used to raise exceptions.
  2350.  
  2351.              If the code to be executed doesn't vary, you may use
  2352.              the eval-BLOCK form to trap run-time errors without
  2353.              incurring the penalty of recompiling each time.  The
  2354.              error, if any, is still returned in $@.  Evaluating
  2355.              a single-quoted string (as EXPR) has the same
  2356.              effect, except that the eval-EXPR form reports syn-
  2357.              tax errors at run time via $@, whereas the eval-
  2358.              BLOCK form reports syntax errors at compile time.
  2359.              The eval-EXPR form is optimized to eval-BLOCK the
  2360.              first time it succeeds.  (Since the replacement side
  2361.              of a substitution is considered a single-quoted
  2362.              string when you use the e modifier, the same optimi-
  2363.              zation occurs there.)  Examples:
  2364.  
  2365.  
  2366.  
  2367.  
  2368.  
  2369.  
  2370.  
  2371.  
  2372.  
  2373. Sprite v1.0                                                    36
  2374.  
  2375.  
  2376.  
  2377.  
  2378.  
  2379.  
  2380. PERL                      User Commands                      PERL
  2381.  
  2382.  
  2383.  
  2384.                   # make divide-by-zero non-fatal
  2385.                   eval { $answer = $a / $b; }; warn $@ if $@;
  2386.  
  2387.                   # optimized to same thing after first use
  2388.                   eval '$answer = $a / $b'; warn $@ if $@;
  2389.  
  2390.                   # a compile-time error
  2391.                   eval { $answer = };
  2392.  
  2393.                   # a run-time error
  2394.                   eval '$answer =';   # sets $@
  2395.  
  2396.  
  2397.      exec(LIST)
  2398.  
  2399.      exec LIST
  2400.              If there is more than one argument in LIST, or if
  2401.              LIST is an array with more than one value, calls
  2402.              execvp() with the arguments in LIST.  If there is
  2403.              only one scalar argument, the argument is checked
  2404.              for shell metacharacters.  If there are any, the
  2405.              entire argument is passed to "/bin/sh -c" for pars-
  2406.              ing.  If there are none, the argument is split into
  2407.              words and passed directly to execvp(), which is more
  2408.              efficient.  Note: exec (and system) do not flush
  2409.              your output buffer, so you may need to set $| to
  2410.              avoid lost output.  Examples:
  2411.  
  2412.                   exec '/bin/echo', 'Your arguments are: ', @ARGV;
  2413.                   exec "sort $outfile | uniq";
  2414.  
  2415.  
  2416.              If you don't really want to execute the first argu-
  2417.              ment, but want to lie to the program you are execut-
  2418.              ing about its own name, you can specify the program
  2419.              you actually want to run by assigning that to a
  2420.              variable and putting the name of the variable in
  2421.              front of the LIST without a comma.  (This always
  2422.              forces interpretation of the LIST as a multi-valued
  2423.              list, even if there is only a single scalar in the
  2424.              list.) Example:
  2425.  
  2426.                   $shell = '/bin/csh';
  2427.                   exec $shell '-sh';       # pretend it's a login shell
  2428.  
  2429.  
  2430.      exit(EXPR)
  2431.  
  2432.      exit EXPR
  2433.              Evaluates EXPR and exits immediately with that
  2434.              value.  Example:
  2435.  
  2436.  
  2437.  
  2438.  
  2439. Sprite v1.0                                                    37
  2440.  
  2441.  
  2442.  
  2443.  
  2444.  
  2445.  
  2446. PERL                      User Commands                      PERL
  2447.  
  2448.  
  2449.  
  2450.                   $ans = <STDIN>;
  2451.                   exit 0 if $ans =~ /^[Xx]/;
  2452.  
  2453.              See also _d_i_e.  If EXPR is omitted, exits with 0
  2454.              status.
  2455.  
  2456.      exp(EXPR)
  2457.  
  2458.      exp EXPR
  2459.              Returns _e to the power of EXPR.  If EXPR is omitted,
  2460.              gives exp($_).
  2461.  
  2462.      fcntl(FILEHANDLE,FUNCTION,SCALAR)
  2463.              Implements the fcntl(2) function.  You'll probably
  2464.              have to say
  2465.  
  2466.                   require "fcntl.ph"; # probably /usr/local/lib/perl/fcntl.ph
  2467.  
  2468.              first to get the correct function definitions.  If
  2469.              fcntl.ph doesn't exist or doesn't have the correct
  2470.              definitions you'll have to roll your own, based on
  2471.              your C header files such as <sys/fcntl.h>.  (There
  2472.              is a perl script called h2ph that comes with the
  2473.              perl kit which may help you in this.) Argument pro-
  2474.              cessing and value return works just like ioctl
  2475.              below.  Note that fcntl will produce a fatal error
  2476.              if used on a machine that doesn't implement
  2477.              fcntl(2).
  2478.  
  2479.      fileno(FILEHANDLE)
  2480.  
  2481.      fileno FILEHANDLE
  2482.              Returns the file descriptor for a filehandle.  Use-
  2483.              ful for constructing bitmaps for select().  If
  2484.              FILEHANDLE is an expression, the value is taken as
  2485.              the name of the filehandle.
  2486.  
  2487.      flock(FILEHANDLE,OPERATION)
  2488.              Calls flock(2) on FILEHANDLE.  See manual page for
  2489.              flock(2) for definition of OPERATION.  Returns true
  2490.              for success, false on failure.  Will produce a fatal
  2491.              error if used on a machine that doesn't implement
  2492.              flock(2).  Here's a mailbox appender for BSD sys-
  2493.              tems.
  2494.  
  2495.  
  2496.  
  2497.  
  2498.  
  2499.  
  2500.  
  2501.  
  2502.  
  2503.  
  2504.  
  2505. Sprite v1.0                                                    38
  2506.  
  2507.  
  2508.  
  2509.  
  2510.  
  2511.  
  2512. PERL                      User Commands                      PERL
  2513.  
  2514.  
  2515.  
  2516.                   $LOCK_SH = 1;
  2517.                   $LOCK_EX = 2;
  2518.                   $LOCK_NB = 4;
  2519.                   $LOCK_UN = 8;
  2520.  
  2521.                   sub lock {
  2522.                       flock(MBOX,$LOCK_EX);
  2523.                       # and, in case someone appended
  2524.                       # while we were waiting...
  2525.                       seek(MBOX, 0, 2);
  2526.                   }
  2527.  
  2528.                   sub unlock {
  2529.                       flock(MBOX,$LOCK_UN);
  2530.                   }
  2531.  
  2532.                   open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  2533.                        || die "Can't open mailbox: $!";
  2534.  
  2535.                   do lock();
  2536.                   print MBOX $msg,"\n\n";
  2537.                   do unlock();
  2538.  
  2539.  
  2540.      fork    Does a fork() call.  Returns the child pid to the
  2541.              parent process and 0 to the child process.  Note:
  2542.              unflushed buffers remain unflushed in both
  2543.              processes, which means you may need to set $| to
  2544.              avoid duplicate output.
  2545.  
  2546.      getc(FILEHANDLE)
  2547.  
  2548.      getc FILEHANDLE
  2549.  
  2550.      getc    Returns the next character from the input file
  2551.              attached to FILEHANDLE, or a null string at EOF.  If
  2552.              FILEHANDLE is omitted, reads from STDIN.
  2553.  
  2554.      getlogin
  2555.              Returns the current login from /etc/utmp, if any.
  2556.              If null, use getpwuid.
  2557.  
  2558.                   $login = getlogin || (getpwuid($<))[0] ||
  2559.              "Somebody";
  2560.  
  2561.  
  2562.      getpeername(SOCKET)
  2563.              Returns the packed sockaddr address of other end of
  2564.              the SOCKET connection.
  2565.  
  2566.  
  2567.  
  2568.  
  2569.  
  2570.  
  2571. Sprite v1.0                                                    39
  2572.  
  2573.  
  2574.  
  2575.  
  2576.  
  2577.  
  2578. PERL                      User Commands                      PERL
  2579.  
  2580.  
  2581.  
  2582.                   # An internet sockaddr
  2583.                   $sockaddr = 'S n a4 x8';
  2584.                   $hersockaddr = getpeername(S);
  2585.                   ($family, $port, $heraddr) =
  2586.                             unpack($sockaddr,$hersockaddr);
  2587.  
  2588.  
  2589.      getpgrp(PID)
  2590.  
  2591.      getpgrp PID
  2592.              Returns the current process group for the specified
  2593.              PID, 0 for the current process.  Will produce a
  2594.              fatal error if used on a machine that doesn't imple-
  2595.              ment getpgrp(2).  If EXPR is omitted, returns pro-
  2596.              cess group of current process.
  2597.  
  2598.      getppid Returns the process id of the parent process.
  2599.  
  2600.      getpriority(WHICH,WHO)
  2601.              Returns the current priority for a process, a pro-
  2602.              cess group, or a user.  (See getpriority(2).) Will
  2603.              produce a fatal error if used on a machine that
  2604.              doesn't implement getpriority(2).
  2605.  
  2606.      getpwnam(NAME)
  2607.  
  2608.      getgrnam(NAME)
  2609.  
  2610.      gethostbyname(NAME)
  2611.  
  2612.      getnetbyname(NAME)
  2613.  
  2614.      getprotobyname(NAME)
  2615.  
  2616.      getpwuid(UID)
  2617.  
  2618.      getgrgid(GID)
  2619.  
  2620.      getservbyname(NAME,PROTO)
  2621.  
  2622.      gethostbyaddr(ADDR,ADDRTYPE)
  2623.  
  2624.      getnetbyaddr(ADDR,ADDRTYPE)
  2625.  
  2626.      getprotobynumber(NUMBER)
  2627.  
  2628.      getservbyport(PORT,PROTO)
  2629.  
  2630.      getpwent
  2631.  
  2632.      getgrent
  2633.  
  2634.  
  2635.  
  2636.  
  2637. Sprite v1.0                                                    40
  2638.  
  2639.  
  2640.  
  2641.  
  2642.  
  2643.  
  2644. PERL                      User Commands                      PERL
  2645.  
  2646.  
  2647.  
  2648.      gethostent
  2649.  
  2650.      getnetent
  2651.  
  2652.      getprotoent
  2653.  
  2654.      getservent
  2655.  
  2656.      setpwent
  2657.  
  2658.      setgrent
  2659.  
  2660.      sethostent(STAYOPEN)
  2661.  
  2662.      setnetent(STAYOPEN)
  2663.  
  2664.      setprotoent(STAYOPEN)
  2665.  
  2666.      setservent(STAYOPEN)
  2667.  
  2668.      endpwent
  2669.  
  2670.      endgrent
  2671.  
  2672.      endhostent
  2673.  
  2674.      endnetent
  2675.  
  2676.      endprotoent
  2677.  
  2678.      endservent
  2679.              These routines perform the same functions as their
  2680.              counterparts in the system library.  The return
  2681.              values from the various get routines are as follows:
  2682.  
  2683.                   ($name,$passwd,$uid,$gid,
  2684.                      $quota,$comment,$gcos,$dir,$shell) = getpw...
  2685.                   ($name,$passwd,$gid,$members) = getgr...
  2686.                   ($name,$aliases,$addrtype,$length,@addrs) = gethost...
  2687.                   ($name,$aliases,$addrtype,$net) = getnet...
  2688.                   ($name,$aliases,$proto) = getproto...
  2689.                   ($name,$aliases,$port,$proto) = getserv...
  2690.  
  2691.              The $members value returned by getgr... is a space
  2692.              separated list of the login names of the members of
  2693.              the group.
  2694.  
  2695.              The @addrs value returned by the gethost... func-
  2696.              tions is a list of the raw addresses returned by the
  2697.              corresponding system library call.  In the Internet
  2698.              domain, each address is four bytes long and you can
  2699.              unpack it by saying something like:
  2700.  
  2701.  
  2702.  
  2703. Sprite v1.0                                                    41
  2704.  
  2705.  
  2706.  
  2707.  
  2708.  
  2709.  
  2710. PERL                      User Commands                      PERL
  2711.  
  2712.  
  2713.  
  2714.                   ($a,$b,$c,$d) = unpack('C4',$addr[0]);
  2715.  
  2716.  
  2717.      getsockname(SOCKET)
  2718.              Returns the packed sockaddr address of this end of
  2719.              the SOCKET connection.
  2720.  
  2721.                   # An internet sockaddr
  2722.                   $sockaddr = 'S n a4 x8';
  2723.                   $mysockaddr = getsockname(S);
  2724.                   ($family, $port, $myaddr) =
  2725.                             unpack($sockaddr,$mysockaddr);
  2726.  
  2727.  
  2728.      getsockopt(SOCKET,LEVEL,OPTNAME)
  2729.              Returns the socket option requested, or undefined if
  2730.              there is an error.
  2731.  
  2732.      gmtime(EXPR)
  2733.  
  2734.      gmtime EXPR
  2735.              Converts a time as returned by the time function to
  2736.              a 9-element array with the time analyzed for the
  2737.              Greenwich timezone.  Typically used as follows:
  2738.  
  2739.              ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2740.                                            gmtime(time);
  2741.  
  2742.              All array elements are numeric, and come straight
  2743.              out of a struct tm.  In particular this means that
  2744.              $mon has the range 0..11 and $wday has the range
  2745.              0..6.  If EXPR is omitted, does gmtime(time).
  2746.  
  2747.      goto LABEL
  2748.              Finds the statement labeled with LABEL and resumes
  2749.              execution there.  Currently you may only go to
  2750.              statements in the main body of the program that are
  2751.              not nested inside a do {} construct.  This statement
  2752.              is not implemented very efficiently, and is here
  2753.              only to make the _s_e_d-to-_p_e_r_l translator easier.  I
  2754.              may change its semantics at any time, consistent
  2755.              with support for translated _s_e_d scripts.  Use it at
  2756.              your own risk.  Better yet, don't use it at all.
  2757.  
  2758.      grep(EXPR,LIST)
  2759.              Evaluates EXPR for each element of LIST (locally
  2760.              setting $_ to each element) and returns the array
  2761.              value consisting of those elements for which the
  2762.              expression evaluated to true.  In a scalar context,
  2763.              returns the number of times the expression was true.
  2764.  
  2765.                   @foo = grep(!/^#/, @bar);    # weed out comments
  2766.  
  2767.  
  2768.  
  2769. Sprite v1.0                                                    42
  2770.  
  2771.  
  2772.  
  2773.  
  2774.  
  2775.  
  2776. PERL                      User Commands                      PERL
  2777.  
  2778.  
  2779.  
  2780.              Note that, since $_ is a reference into the array
  2781.              value, it can be used to modify the elements of the
  2782.              array.  While this is useful and supported, it can
  2783.              cause bizarre results if the LIST is not a named
  2784.              array.
  2785.  
  2786.      hex(EXPR)
  2787.  
  2788.      hex EXPR
  2789.              Returns the decimal value of EXPR interpreted as an
  2790.              hex string.  (To interpret strings that might start
  2791.              with 0 or 0x see oct().) If EXPR is omitted, uses
  2792.              $_.
  2793.  
  2794.      index(STR,SUBSTR,POSITION)
  2795.  
  2796.      index(STR,SUBSTR)
  2797.              Returns the position of the first occurrence of
  2798.              SUBSTR in STR at or after POSITION.  If POSITION is
  2799.              omitted, starts searching from the beginning of the
  2800.              string.  The return value is based at 0, or whatever
  2801.              you've set the $[ variable to.  If the substring is
  2802.              not found, returns one less than the base, ordi-
  2803.              narily -1.
  2804.  
  2805.      int(EXPR)
  2806.  
  2807.      int EXPR
  2808.              Returns the integer portion of EXPR.  If EXPR is
  2809.              omitted, uses $_.
  2810.  
  2811.      ioctl(FILEHANDLE,FUNCTION,SCALAR)
  2812.              Implements the ioctl(2) function.  You'll probably
  2813.              have to say
  2814.  
  2815.                   require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph
  2816.  
  2817.              first to get the correct function definitions.  If
  2818.              ioctl.ph doesn't exist or doesn't have the correct
  2819.              definitions you'll have to roll your own, based on
  2820.              your C header files such as <sys/ioctl.h>.  (There
  2821.              is a perl script called h2ph that comes with the
  2822.              perl kit which may help you in this.) SCALAR will be
  2823.              read and/or written depending on the FUNCTION--a
  2824.              pointer to the string value of SCALAR will be passed
  2825.              as the third argument of the actual ioctl call.  (If
  2826.              SCALAR has no string value but does have a numeric
  2827.              value, that value will be passed rather than a
  2828.              pointer to the string value.  To guarantee this to
  2829.              be true, add a 0 to the scalar before using it.) The
  2830.              pack() and unpack() functions are useful for manipu-
  2831.              lating the values of structures used by ioctl().
  2832.  
  2833.  
  2834.  
  2835. Sprite v1.0                                                    43
  2836.  
  2837.  
  2838.  
  2839.  
  2840.  
  2841.  
  2842. PERL                      User Commands                      PERL
  2843.  
  2844.  
  2845.  
  2846.              The following example sets the erase character to
  2847.              DEL.
  2848.  
  2849.                   require 'ioctl.ph';
  2850.                   $sgttyb_t = "ccccs";          # 4 chars and a short
  2851.                   if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
  2852.                        @ary = unpack($sgttyb_t,$sgttyb);
  2853.                        $ary[2] = 127;
  2854.                        $sgttyb = pack($sgttyb_t,@ary);
  2855.                        ioctl(STDIN,$TIOCSETP,$sgttyb)
  2856.                             || die "Can't ioctl: $!";
  2857.                   }
  2858.  
  2859.              The return value of ioctl (and fcntl) is as follows:
  2860.  
  2861.                   if OS returns:           perl returns:
  2862.                     -1                       undefined value
  2863.                     0                        string "0 but true"
  2864.                     anything else            that number
  2865.  
  2866.              Thus perl returns true on success and false on
  2867.              failure, yet you can still easily determine the
  2868.              actual value returned by the operating system:
  2869.  
  2870.                   ($retval = ioctl(...)) || ($retval = -1);
  2871.                   printf "System returned %d\n", $retval;
  2872.  
  2873.      join(EXPR,LIST)
  2874.  
  2875.      join(EXPR,ARRAY)
  2876.              Joins the separate strings of LIST or ARRAY into a
  2877.              single string with fields separated by the value of
  2878.              EXPR, and returns the string.  Example:
  2879.  
  2880.              $_ = join(':',
  2881.                        $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  2882.  
  2883.              See _s_p_l_i_t.
  2884.  
  2885.      keys(ASSOC_ARRAY)
  2886.  
  2887.      keys ASSOC_ARRAY
  2888.              Returns a normal array consisting of all the keys of
  2889.              the named associative array.  The keys are returned
  2890.              in an apparently random order, but it is the same
  2891.              order as either the values() or each() function pro-
  2892.              duces (given that the associative array has not been
  2893.              modified).  Here is yet another way to print your
  2894.              environment:
  2895.  
  2896.  
  2897.  
  2898.  
  2899.  
  2900.  
  2901. Sprite v1.0                                                    44
  2902.  
  2903.  
  2904.  
  2905.  
  2906.  
  2907.  
  2908. PERL                      User Commands                      PERL
  2909.  
  2910.  
  2911.  
  2912.                   @keys = keys %ENV;
  2913.                   @values = values %ENV;
  2914.                   while ($#keys >= 0) {
  2915.                        print pop(@keys), '=', pop(@values), "\n";
  2916.                   }
  2917.  
  2918.              or how about sorted by key:
  2919.  
  2920.                   foreach $key (sort(keys %ENV)) {
  2921.                        print $key, '=', $ENV{$key}, "\n";
  2922.                   }
  2923.  
  2924.  
  2925.      kill(LIST)
  2926.  
  2927.      kill LIST
  2928.              Sends a signal to a list of processes.  The first
  2929.              element of the list must be the signal to send.
  2930.              Returns the number of processes successfully sig-
  2931.              naled.
  2932.  
  2933.                   $cnt = kill 1, $child1, $child2;
  2934.                   kill 9, @goners;
  2935.  
  2936.              If the signal is negative, kills process groups
  2937.              instead of processes.  (On System V, a negative _p_r_o_-
  2938.              _c_e_s_s number will also kill process groups, but
  2939.              that's not portable.) You may use a signal name in
  2940.              quotes.
  2941.  
  2942.      last LABEL
  2943.  
  2944.      last    The _l_a_s_t command is like the _b_r_e_a_k statement in C
  2945.              (as used in loops); it immediately exits the loop in
  2946.              question.  If the LABEL is omitted, the command
  2947.              refers to the innermost enclosing loop.  The _c_o_n_-
  2948.              _t_i_n_u_e block, if any, is not executed:
  2949.  
  2950.                   line: while (<STDIN>) {
  2951.                        last line if /^$/;  # exit when done with header
  2952.                        ...
  2953.                   }
  2954.  
  2955.  
  2956.      length(EXPR)
  2957.  
  2958.      length EXPR
  2959.              Returns the length in characters of the value of
  2960.              EXPR.  If EXPR is omitted, returns length of $_.
  2961.  
  2962.      link(OLDFILE,NEWFILE)
  2963.              Creates a new filename linked to the old filename.
  2964.  
  2965.  
  2966.  
  2967. Sprite v1.0                                                    45
  2968.  
  2969.  
  2970.  
  2971.  
  2972.  
  2973.  
  2974. PERL                      User Commands                      PERL
  2975.  
  2976.  
  2977.  
  2978.              Returns 1 for success, 0 otherwise.
  2979.  
  2980.      listen(SOCKET,QUEUESIZE)
  2981.              Does the same thing that the listen system call
  2982.              does.  Returns true if it succeeded, false other-
  2983.              wise.  See example in section on Interprocess Com-
  2984.              munication.
  2985.  
  2986.      local(LIST)
  2987.              Declares the listed variables to be local to the
  2988.              enclosing block, subroutine, eval or "do".  All the
  2989.              listed elements must be legal lvalues.  This opera-
  2990.              tor works by saving the current values of those
  2991.              variables in LIST on a hidden stack and restoring
  2992.              them upon exiting the block, subroutine or eval.
  2993.              This means that called subroutines can also refer-
  2994.              ence the local variable, but not the global one.
  2995.              The LIST may be assigned to if desired, which allows
  2996.              you to initialize your local variables.  (If no ini-
  2997.              tializer is given for a particular variable, it is
  2998.              created with an undefined value.) Commonly this is
  2999.              used to name the parameters to a subroutine.  Exam-
  3000.              ples:
  3001.  
  3002.                   sub RANGEVAL {
  3003.                        local($min, $max, $thunk) = @_;
  3004.                        local($result) = '';
  3005.                        local($i);
  3006.  
  3007.                        # Presumably $thunk makes reference to $i
  3008.  
  3009.                        for ($i = $min; $i < $max; $i++) {
  3010.                             $result .= eval $thunk;
  3011.                        }
  3012.  
  3013.                        $result;
  3014.                   }
  3015.  
  3016.                   if ($sw eq '-v') {
  3017.                       # init local array with global array
  3018.                       local(@ARGV) = @ARGV;
  3019.                       unshift(@ARGV,'echo');
  3020.                       system @ARGV;
  3021.                   }
  3022.                   # @ARGV restored
  3023.  
  3024.                   # temporarily add to digits associative array
  3025.                   if ($base12) {
  3026.                        # (NOTE: not claiming this is efficient!)
  3027.                        local(%digits) = (%digits,'t',10,'e',11);
  3028.                        do parse_num();
  3029.                   }
  3030.  
  3031.  
  3032.  
  3033. Sprite v1.0                                                    46
  3034.  
  3035.  
  3036.  
  3037.  
  3038.  
  3039.  
  3040. PERL                      User Commands                      PERL
  3041.  
  3042.  
  3043.  
  3044.              Note that local() is a run-time command, and so gets
  3045.              executed every time through a loop, using up more
  3046.              stack storage each time until it's all released at
  3047.              once when the loop is exited.
  3048.  
  3049.      localtime(EXPR)
  3050.  
  3051.      localtime EXPR
  3052.              Converts a time as returned by the time function to
  3053.              a 9-element array with the time analyzed for the
  3054.              local timezone.  Typically used as follows:
  3055.  
  3056.              ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  3057.                                            localtime(time);
  3058.  
  3059.              All array elements are numeric, and come straight
  3060.              out of a struct tm.  In particular this means that
  3061.              $mon has the range 0..11 and $wday has the range
  3062.              0..6.  If EXPR is omitted, does localtime(time).
  3063.  
  3064.      log(EXPR)
  3065.  
  3066.      log EXPR
  3067.              Returns logarithm (base _e) of EXPR.  If EXPR is
  3068.              omitted, returns log of $_.
  3069.  
  3070.      lstat(FILEHANDLE)
  3071.  
  3072.      lstat FILEHANDLE
  3073.  
  3074.      lstat(EXPR)
  3075.  
  3076.      lstat SCALARVARIABLE
  3077.              Does the same thing as the stat() function, but
  3078.              stats a symbolic link instead of the file the sym-
  3079.              bolic link points to.  If symbolic links are unim-
  3080.              plemented on your system, a normal stat is done.
  3081.  
  3082.      m/PATTERN/gio
  3083.  
  3084.      /PATTERN/gio
  3085.              Searches a string for a pattern match, and returns
  3086.              true (1) or false ('').  If no string is specified
  3087.              via the =~ or !~ operator, the $_ string is
  3088.              searched.  (The string specified with =~ need not be
  3089.              an lvalue--it may be the result of an expression
  3090.              evaluation, but remember the =~ binds rather
  3091.              tightly.) See also the section on regular expres-
  3092.              sions.
  3093.  
  3094.              If / is the delimiter then the initial 'm' is
  3095.              optional.  With the 'm' you can use any pair of
  3096.  
  3097.  
  3098.  
  3099. Sprite v1.0                                                    47
  3100.  
  3101.  
  3102.  
  3103.  
  3104.  
  3105.  
  3106. PERL                      User Commands                      PERL
  3107.  
  3108.  
  3109.  
  3110.              non-alphanumeric characters as delimiters.  This is
  3111.              particularly useful for matching Unix path names
  3112.              that contain '/'.  If the final delimiter is fol-
  3113.              lowed by the optional letter 'i', the matching is
  3114.              done in a case-insensitive manner.  PATTERN may con-
  3115.              tain references to scalar variables, which will be
  3116.              interpolated (and the pattern recompiled) every time
  3117.              the pattern search is evaluated.  (Note that $) and
  3118.              $| may not be interpolated because they look like
  3119.              end-of-string tests.) If you want such a pattern to
  3120.              be compiled only once, add an "o" after the trailing
  3121.              delimiter.  This avoids expensive run-time recompi-
  3122.              lations, and is useful when the value you are inter-
  3123.              polating won't change over the life of the script.
  3124.              If the PATTERN evaluates to a null string, the most
  3125.              recent successful regular expression is used
  3126.              instead.
  3127.  
  3128.              If used in a context that requires an array value, a
  3129.              pattern match returns an array consisting of the
  3130.              subexpressions matched by the parentheses in the
  3131.              pattern, i.e. ($1, $2, $3...).  It does NOT actually
  3132.              set $1, $2, etc. in this case, nor does it set $+,
  3133.              $`, $& or $'.  If the match fails, a null array is
  3134.              returned.  If the match succeeds, but there were no
  3135.              parentheses, an array value of (1) is returned.
  3136.  
  3137.              Examples:
  3138.  
  3139.                  open(tty, '/dev/tty');
  3140.                  <tty> =~ /^y/i && do foo();    # do foo if desired
  3141.  
  3142.                  if (/Version: *([0-9.]*)/) { $version = $1; }
  3143.  
  3144.                  next if m#^/usr/spool/uucp#;
  3145.  
  3146.                  # poor man's grep
  3147.                  $arg = shift;
  3148.                  while (<>) {
  3149.                       print if /$arg/o;    # compile only once
  3150.                  }
  3151.  
  3152.                  if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
  3153.  
  3154.              This last example splits $foo into the first two
  3155.              words and the remainder of the line, and assigns
  3156.              those three fields to $F1, $F2 and $Etc.  The condi-
  3157.              tional is true if any variables were assigned, i.e.
  3158.              if the pattern matched.
  3159.  
  3160.              The "g" modifier specifies global pattern
  3161.              matching--that is, matching as many times as
  3162.  
  3163.  
  3164.  
  3165. Sprite v1.0                                                    48
  3166.  
  3167.  
  3168.  
  3169.  
  3170.  
  3171.  
  3172. PERL                      User Commands                      PERL
  3173.  
  3174.  
  3175.  
  3176.              possible within the string.  How it behaves depends
  3177.              on the context.  In an array context, it returns a
  3178.              list of all the substrings matched by all the
  3179.              parentheses in the regular expression.  If there are
  3180.              no parentheses, it returns a list of all the matched
  3181.              strings, as if there were parentheses around the
  3182.              whole pattern.  In a scalar context, it iterates
  3183.              through the string, returning TRUE each time it
  3184.              matches, and FALSE when it eventually runs out of
  3185.              matches.  (In other words, it remembers where it
  3186.              left off last time and restarts the search at that
  3187.              point.)  It presumes that you have not modified the
  3188.              string since the last match.  Modifying the string
  3189.              between matches may result in undefined behavior.
  3190.              (You can actually get away with in-place modifica-
  3191.              tions via substr() that do not change the length of
  3192.              the entire string.  In general, however, you should
  3193.              be using s///g for such modifications.)  Examples:
  3194.  
  3195.                   # array context
  3196.                   ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
  3197.  
  3198.                   # scalar context
  3199.                   $/ = 1; $* = 1;
  3200.                   while ($paragraph = <>) {
  3201.                       while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
  3202.                        $sentences++;
  3203.                       }
  3204.                   }
  3205.                   print "$sentences\n";
  3206.  
  3207.  
  3208.      mkdir(FILENAME,MODE)
  3209.              Creates the directory specified by FILENAME, with
  3210.              permissions specified by MODE (as modified by
  3211.              umask).  If it succeeds it returns 1, otherwise it
  3212.              returns 0 and sets $! (errno).
  3213.  
  3214.      msgctl(ID,CMD,ARG)
  3215.              Calls the System V IPC function msgctl.  If CMD is
  3216.              &IPC_STAT, then ARG must be a variable which will
  3217.              hold the returned msqid_ds structure.  Returns like
  3218.              ioctl: the undefined value for error, "0 but true"
  3219.              for zero, or the actual return value otherwise.
  3220.  
  3221.      msgget(KEY,FLAGS)
  3222.              Calls the System V IPC function msgget.  Returns the
  3223.              message queue id, or the undefined value if there is
  3224.              an error.
  3225.  
  3226.  
  3227.  
  3228.  
  3229.  
  3230.  
  3231. Sprite v1.0                                                    49
  3232.  
  3233.  
  3234.  
  3235.  
  3236.  
  3237.  
  3238. PERL                      User Commands                      PERL
  3239.  
  3240.  
  3241.  
  3242.      msgsnd(ID,MSG,FLAGS)
  3243.              Calls the System V IPC function msgsnd to send the
  3244.              message MSG to the message queue ID.  MSG must begin
  3245.              with the long integer message type, which may be
  3246.              created with pack("L", $type).  Returns true if suc-
  3247.              cessful, or false if there is an error.
  3248.  
  3249.      msgrcv(ID,VAR,SIZE,TYPE,FLAGS)
  3250.              Calls the System V IPC function msgrcv to receive a
  3251.              message from message queue ID into variable VAR with
  3252.              a maximum message size of SIZE.  Note that if a mes-
  3253.              sage is received, the message type will be the first
  3254.              thing in VAR, and the maximum length of VAR is SIZE
  3255.              plus the size of the message type.  Returns true if
  3256.              successful, or false if there is an error.
  3257.  
  3258.      next LABEL
  3259.  
  3260.      next    The _n_e_x_t command is like the _c_o_n_t_i_n_u_e statement in
  3261.              C; it starts the next iteration of the loop:
  3262.  
  3263.                   line: while (<STDIN>) {
  3264.                        next line if /^#/;  # discard comments
  3265.                        ...
  3266.                   }
  3267.  
  3268.              Note that if there were a _c_o_n_t_i_n_u_e block on the
  3269.              above, it would get executed even on discarded
  3270.              lines.  If the LABEL is omitted, the command refers
  3271.              to the innermost enclosing loop.
  3272.  
  3273.      oct(EXPR)
  3274.  
  3275.      oct EXPR
  3276.              Returns the decimal value of EXPR interpreted as an
  3277.              octal string.  (If EXPR happens to start off with
  3278.              0x, interprets it as a hex string instead.) The fol-
  3279.              lowing will handle decimal, octal and hex in the
  3280.              standard notation:
  3281.  
  3282.                   $val = oct($val) if $val =~ /^0/;
  3283.  
  3284.              If EXPR is omitted, uses $_.
  3285.  
  3286.      open(FILEHANDLE,EXPR)
  3287.  
  3288.      open(FILEHANDLE)
  3289.  
  3290.      open FILEHANDLE
  3291.              Opens the file whose filename is given by EXPR, and
  3292.              associates it with FILEHANDLE.  If FILEHANDLE is an
  3293.              expression, its value is used as the name of the
  3294.  
  3295.  
  3296.  
  3297. Sprite v1.0                                                    50
  3298.  
  3299.  
  3300.  
  3301.  
  3302.  
  3303.  
  3304. PERL                      User Commands                      PERL
  3305.  
  3306.  
  3307.  
  3308.              real filehandle wanted.  If EXPR is omitted, the
  3309.              scalar variable of the same name as the FILEHANDLE
  3310.              contains the filename.  If the filename begins with
  3311.              "<" or nothing, the file is opened for input.  If
  3312.              the filename begins with ">", the file is opened for
  3313.              output.  If the filename begins with ">>", the file
  3314.              is opened for appending.  (You can put a '+' in
  3315.              front of the '>' or '<' to indicate that you want
  3316.              both read and write access to the file.) If the
  3317.              filename begins with "|", the filename is inter-
  3318.              preted as a command to which output is to be piped,
  3319.              and if the filename ends with a "|", the filename is
  3320.              interpreted as command which pipes input to us.
  3321.              (You may not have a command that pipes both in and
  3322.              out.) Opening '-' opens _S_T_D_I_N and opening '>-' opens
  3323.              _S_T_D_O_U_T.  Open returns non-zero upon success, the
  3324.              undefined value otherwise.  If the open involved a
  3325.              pipe, the return value happens to be the pid of the
  3326.              subprocess.  Examples:
  3327.  
  3328.                   $article = 100;
  3329.                   open article || die "Can't find article $article: $!\n";
  3330.                   while (<article>) {...
  3331.  
  3332.                   open(LOG, '>>/usr/spool/news/twitlog');
  3333.                                       # (log is reserved)
  3334.  
  3335.                   open(article, "caesar <$article |");
  3336.                                       # decrypt article
  3337.  
  3338.                   open(extract, "|sort >/tmp/Tmp$$");
  3339.                                       # $$ is our process#
  3340.  
  3341.                   # process argument list of files along with any includes
  3342.  
  3343.                   foreach $file (@ARGV) {
  3344.                        do process($file, 'fh00');    # no pun intended
  3345.                   }
  3346.  
  3347.                   sub process {
  3348.                        local($filename, $input) = @_;
  3349.                        $input++;      # this is a string increment
  3350.                        unless (open($input, $filename)) {
  3351.                             print STDERR "Can't open $filename: $!\n";
  3352.                             return;
  3353.                        }
  3354.                        while (<$input>) {       # note use of indirection
  3355.                             if (/^#include "(.*)"/) {
  3356.                                  do process($1, $input);
  3357.                                  next;
  3358.                             }
  3359.                             ...       # whatever
  3360.  
  3361.  
  3362.  
  3363. Sprite v1.0                                                    51
  3364.  
  3365.  
  3366.  
  3367.  
  3368.  
  3369.  
  3370. PERL                      User Commands                      PERL
  3371.  
  3372.  
  3373.  
  3374.                        }
  3375.                   }
  3376.  
  3377.              You may also, in the Bourne shell tradition, specify
  3378.              an EXPR beginning with ">&", in which case the rest
  3379.              of the string is interpreted as the name of a
  3380.              filehandle (or file descriptor, if numeric) which is
  3381.              to be duped and opened.  You may use & after >, >>,
  3382.              <, +>, +>> and +<.  The mode you specify should
  3383.              match the mode of the original filehandle.  Here is
  3384.              a script that saves, redirects, and restores _S_T_D_O_U_T
  3385.              and _S_T_D_E_R_R:
  3386.  
  3387.                   #!/usr/bin/perl
  3388.                   open(SAVEOUT, ">&STDOUT");
  3389.                   open(SAVEERR, ">&STDERR");
  3390.  
  3391.                   open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  3392.                   open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  3393.  
  3394.                   select(STDERR); $| = 1;       # make unbuffered
  3395.                   select(STDOUT); $| = 1;       # make unbuffered
  3396.  
  3397.                   print STDOUT "stdout 1\n";    # this works for
  3398.                   print STDERR "stderr 1\n";    # subprocesses too
  3399.  
  3400.                   close(STDOUT);
  3401.                   close(STDERR);
  3402.  
  3403.                   open(STDOUT, ">&SAVEOUT");
  3404.                   open(STDERR, ">&SAVEERR");
  3405.  
  3406.                   print STDOUT "stdout 2\n";
  3407.                   print STDERR "stderr 2\n";
  3408.  
  3409.              If you open a pipe on the command "-", i.e. either
  3410.              "|-" or "-|", then there is an implicit fork done,
  3411.              and the return value of open is the pid of the child
  3412.              within the parent process, and 0 within the child
  3413.              process.  (Use defined($pid) to determine if the
  3414.              open was successful.) The filehandle behaves nor-
  3415.              mally for the parent, but i/o to that filehandle is
  3416.              piped from/to the _S_T_D_O_U_T/_S_T_D_I_N of the child process.
  3417.              In the child process the filehandle isn't opened--
  3418.              i/o happens from/to the new _S_T_D_O_U_T or _S_T_D_I_N.  Typi-
  3419.              cally this is used like the normal piped open when
  3420.              you want to exercise more control over just how the
  3421.              pipe command gets executed, such as when you are
  3422.              running setuid, and don't want to have to scan shell
  3423.              commands for metacharacters.  The following pairs
  3424.              are more or less equivalent:
  3425.  
  3426.  
  3427.  
  3428.  
  3429. Sprite v1.0                                                    52
  3430.  
  3431.  
  3432.  
  3433.  
  3434.  
  3435.  
  3436. PERL                      User Commands                      PERL
  3437.  
  3438.  
  3439.  
  3440.                   open(FOO, "|tr '[a-z]' '[A-Z]'");
  3441.                   open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
  3442.  
  3443.                   open(FOO, "cat -n '$file'|");
  3444.                   open(FOO, "-|") || exec 'cat', '-n', $file;
  3445.  
  3446.              Explicitly closing any piped filehandle causes the
  3447.              parent process to wait for the child to finish, and
  3448.              returns the status value in $?.  Note: on any opera-
  3449.              tion which may do a fork, unflushed buffers remain
  3450.              unflushed in both processes, which means you may
  3451.              need to set $| to avoid duplicate output.
  3452.  
  3453.              The filename that is passed to open will have lead-
  3454.              ing and trailing whitespace deleted.  In order to
  3455.              open a file with arbitrary weird characters in it,
  3456.              it's necessary to protect any leading and trailing
  3457.              whitespace thusly:
  3458.  
  3459.                      $file =~ s#^(\s)#./$1#;
  3460.                      open(FOO, "< $file\0");
  3461.  
  3462.  
  3463.      opendir(DIRHANDLE,EXPR)
  3464.              Opens a directory named EXPR for processing by read-
  3465.              dir(), telldir(), seekdir(), rewinddir() and
  3466.              closedir().  Returns true if successful.  DIRHANDLEs
  3467.              have their own namespace separate from FILEHANDLEs.
  3468.  
  3469.      ord(EXPR)
  3470.  
  3471.      ord EXPR
  3472.              Returns the numeric ascii value of the first charac-
  3473.              ter of EXPR.  If EXPR is omitted, uses $_.
  3474.  
  3475.      pack(TEMPLATE,LIST)
  3476.              Takes an array or list of values and packs it into a
  3477.              binary structure, returning the string containing
  3478.              the structure.  The TEMPLATE is a sequence of char-
  3479.              acters that give the order and type of values, as
  3480.              follows:
  3481.  
  3482.                   A    An ascii string, will be space padded.
  3483.                   a    An ascii string, will be null padded.
  3484.                   c    A signed char value.
  3485.                   C    An unsigned char value.
  3486.                   s    A signed short value.
  3487.                   S    An unsigned short value.
  3488.                   i    A signed integer value.
  3489.                   I    An unsigned integer value.
  3490.                   l    A signed long value.
  3491.                   L    An unsigned long value.
  3492.  
  3493.  
  3494.  
  3495. Sprite v1.0                                                    53
  3496.  
  3497.  
  3498.  
  3499.  
  3500.  
  3501.  
  3502. PERL                      User Commands                      PERL
  3503.  
  3504.  
  3505.  
  3506.                   n    A short in "network" order.
  3507.                   N    A long in "network" order.
  3508.                   f    A single-precision float in the native format.
  3509.                   d    A double-precision float in the native format.
  3510.                   p    A pointer to a string.
  3511.                   v    A short in "VAX" (little-endian) order.
  3512.                   V    A long in "VAX" (little-endian) order.
  3513.                   x    A null byte.
  3514.                   X    Back up a byte.
  3515.                   @    Null fill to absolute position.
  3516.                   u    A uuencoded string.
  3517.                   b    A bit string (ascending bit order, like vec()).
  3518.                   B    A bit string (descending bit order).
  3519.                   h    A hex string (low nybble first).
  3520.                   H    A hex string (high nybble first).
  3521.  
  3522.              Each letter may optionally be followed by a number
  3523.              which gives a repeat count.  With all types except
  3524.              "a", "A", "b", "B", "h" and "H", the pack function
  3525.              will gobble up that many values from the LIST.  A *
  3526.              for the repeat count means to use however many items
  3527.              are left.  The "a" and "A" types gobble just one
  3528.              value, but pack it as a string of length count, pad-
  3529.              ding with nulls or spaces as necessary.  (When
  3530.              unpacking, "A" strips trailing spaces and nulls, but
  3531.              "a" does not.) Likewise, the "b" and "B" fields pack
  3532.              a string that many bits long.  The "h" and "H"
  3533.              fields pack a string that many nybbles long.  Real
  3534.              numbers (floats and doubles) are in the native
  3535.              machine format only; due to the multiplicity of
  3536.              floating formats around, and the lack of a standard
  3537.              "network" representation, no facility for inter-
  3538.              change has been made.  This means that packed float-
  3539.              ing point data written on one machine may not be
  3540.              readable on another - even if both use IEEE floating
  3541.              point arithmetic (as the endian-ness of the memory
  3542.              representation is not part of the IEEE spec).  Note
  3543.              that perl uses doubles internally for all numeric
  3544.              calculation, and converting from double -> float ->
  3545.              double will lose precision (i.e. unpack("f",
  3546.              pack("f", $foo)) will not in general equal $foo).
  3547.              Examples:
  3548.  
  3549.                   $foo = pack("cccc",65,66,67,68);
  3550.                   # foo eq "ABCD"
  3551.                   $foo = pack("c4",65,66,67,68);
  3552.                   # same thing
  3553.  
  3554.                   $foo = pack("ccxxcc",65,66,67,68);
  3555.                   # foo eq "AB\0\0CD"
  3556.  
  3557.                   $foo = pack("s2",1,2);
  3558.  
  3559.  
  3560.  
  3561. Sprite v1.0                                                    54
  3562.  
  3563.  
  3564.  
  3565.  
  3566.  
  3567.  
  3568. PERL                      User Commands                      PERL
  3569.  
  3570.  
  3571.  
  3572.                   # "\1\0\2\0" on little-endian
  3573.                   # "\0\1\0\2" on big-endian
  3574.  
  3575.                   $foo = pack("a4","abcd","x","y","z");
  3576.                   # "abcd"
  3577.  
  3578.                   $foo = pack("aaaa","abcd","x","y","z");
  3579.                   # "axyz"
  3580.  
  3581.                   $foo = pack("a14","abcdefg");
  3582.                   # "abcdefg\0\0\0\0\0\0\0"
  3583.  
  3584.                   $foo = pack("i9pl", gmtime);
  3585.                   # a real struct tm (on my system anyway)
  3586.  
  3587.                   sub bintodec {
  3588.                       unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  3589.                   }
  3590.              The same template may generally also be used in the
  3591.              unpack function.
  3592.  
  3593.      pipe(READHANDLE,WRITEHANDLE)
  3594.              Opens a pair of connected pipes like the correspond-
  3595.              ing system call.  Note that if you set up a loop of
  3596.              piped processes, deadlock can occur unless you are
  3597.              very careful.  In addition, note that perl's pipes
  3598.              use stdio buffering, so you may need to set $| to
  3599.              flush your WRITEHANDLE after each command, depending
  3600.              on the application.  [Requires version 3.0
  3601.              patchlevel 9.]
  3602.  
  3603.      pop(ARRAY)
  3604.  
  3605.      pop ARRAY
  3606.              Pops and returns the last value of the array, shor-
  3607.              tening the array by 1.  Has the same effect as
  3608.  
  3609.                   $tmp = $ARRAY[$#ARRAY--];
  3610.  
  3611.              If there are no elements in the array, returns the
  3612.              undefined value.
  3613.  
  3614.      print(FILEHANDLE LIST)
  3615.  
  3616.      print(LIST)
  3617.  
  3618.      print FILEHANDLE LIST
  3619.  
  3620.      print LIST
  3621.  
  3622.      print   Prints a string or a comma-separated list of
  3623.              strings.  Returns non-zero if successful.
  3624.  
  3625.  
  3626.  
  3627. Sprite v1.0                                                    55
  3628.  
  3629.  
  3630.  
  3631.  
  3632.  
  3633.  
  3634. PERL                      User Commands                      PERL
  3635.  
  3636.  
  3637.  
  3638.              FILEHANDLE may be a scalar variable name, in which
  3639.              case the variable contains the name of the filehan-
  3640.              dle, thus introducing one level of indirection.
  3641.              (NOTE: If FILEHANDLE is a variable and the next
  3642.              token is a term, it may be misinterpreted as an
  3643.              operator unless you interpose a + or put parens
  3644.              around the arguments.) If FILEHANDLE is omitted,
  3645.              prints by default to standard output (or to the last
  3646.              selected output channel--see select()).  If LIST is
  3647.              also omitted, prints $_ to _S_T_D_O_U_T.  To set the
  3648.              default output channel to something other than
  3649.              _S_T_D_O_U_T use the select operation.  Note that, because
  3650.              print takes a LIST, anything in the LIST is
  3651.              evaluated in an array context, and any subroutine
  3652.              that you call will have one or more of its expres-
  3653.              sions evaluated in an array context.  Also be care-
  3654.              ful not to follow the print keyword with a left
  3655.              parenthesis unless you want the corresponding right
  3656.              parenthesis to terminate the arguments to the
  3657.              print--interpose a + or put parens around all the
  3658.              arguments.
  3659.  
  3660.      printf(FILEHANDLE LIST)
  3661.  
  3662.      printf(LIST)
  3663.  
  3664.      printf FILEHANDLE LIST
  3665.  
  3666.      printf LIST
  3667.              Equivalent to a "print FILEHANDLE sprintf(LIST)".
  3668.  
  3669.      push(ARRAY,LIST)
  3670.              Treats ARRAY (@ is optional) as a stack, and pushes
  3671.              the values of LIST onto the end of ARRAY.  The
  3672.              length of ARRAY increases by the length of LIST.
  3673.              Has the same effect as
  3674.  
  3675.                  for $value (LIST) {
  3676.                       $ARRAY[++$#ARRAY] = $value;
  3677.                  }
  3678.  
  3679.              but is more efficient.
  3680.  
  3681.      q/STRING/
  3682.  
  3683.      qq/STRING/
  3684.  
  3685.      qx/STRING/
  3686.              These are not really functions, but simply syntactic
  3687.              sugar to let you avoid putting too many backslashes
  3688.              into quoted strings.  The q operator is a general-
  3689.              ized single quote, and the qq operator a generalized
  3690.  
  3691.  
  3692.  
  3693. Sprite v1.0                                                    56
  3694.  
  3695.  
  3696.  
  3697.  
  3698.  
  3699.  
  3700. PERL                      User Commands                      PERL
  3701.  
  3702.  
  3703.  
  3704.              double quote.  The qx operator is a generalized
  3705.              backquote.  Any non-alphanumeric delimiter can be
  3706.              used in place of /, including newline.  If the del-
  3707.              imiter is an opening bracket or parenthesis, the
  3708.              final delimiter will be the corresponding closing
  3709.              bracket or parenthesis.  (Embedded occurrences of
  3710.              the closing bracket need to be backslashed as
  3711.              usual.) Examples:
  3712.  
  3713.                   $foo = q!I said, "You said, 'She said it.'"!;
  3714.                   $bar = q('This is it.');
  3715.                   $today = qx{ date };
  3716.                   $_ .= qq
  3717.              *** The previous line contains the naughty word "$&".\n
  3718.                        if /(ibm|apple|awk)/;      # :-)
  3719.  
  3720.  
  3721.      rand(EXPR)
  3722.  
  3723.      rand EXPR
  3724.  
  3725.      rand    Returns a random fractional number between 0 and the
  3726.              value of EXPR.  (EXPR should be positive.) If EXPR
  3727.              is omitted, returns a value between 0 and 1.  See
  3728.              also srand().
  3729.  
  3730.      read(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3731.  
  3732.      read(FILEHANDLE,SCALAR,LENGTH)
  3733.              Attempts to read LENGTH bytes of data into variable
  3734.              SCALAR from the specified FILEHANDLE.  Returns the
  3735.              number of bytes actually read, or undef if there was
  3736.              an error.  SCALAR will be grown or shrunk to the
  3737.              length actually read.  An OFFSET may be specified to
  3738.              place the read data at some other place than the
  3739.              beginning of the string.  This call is actually
  3740.              implemented in terms of stdio's fread call.  To get
  3741.              a true read system call, see sysread.
  3742.  
  3743.      readdir(DIRHANDLE)
  3744.  
  3745.      readdir DIRHANDLE
  3746.              Returns the next directory entry for a directory
  3747.              opened by opendir().  If used in an array context,
  3748.              returns all the rest of the entries in the direc-
  3749.              tory.  If there are no more entries, returns an
  3750.              undefined value in a scalar context or a null list
  3751.              in an array context.
  3752.  
  3753.  
  3754.  
  3755.  
  3756.  
  3757.  
  3758.  
  3759. Sprite v1.0                                                    57
  3760.  
  3761.  
  3762.  
  3763.  
  3764.  
  3765.  
  3766. PERL                      User Commands                      PERL
  3767.  
  3768.  
  3769.  
  3770.      readlink(EXPR)
  3771.  
  3772.      readlink EXPR
  3773.              Returns the value of a symbolic link, if symbolic
  3774.              links are implemented.  If not, gives a fatal error.
  3775.              If there is some system error, returns the undefined
  3776.              value and sets $! (errno).  If EXPR is omitted, uses
  3777.              $_.
  3778.  
  3779.      recv(SOCKET,SCALAR,LEN,FLAGS)
  3780.              Receives a message on a socket.  Attempts to receive
  3781.              LENGTH bytes of data into variable SCALAR from the
  3782.              specified SOCKET filehandle.  Returns the address of
  3783.              the sender, or the undefined value if there's an
  3784.              error.  SCALAR will be grown or shrunk to the length
  3785.              actually read.  Takes the same flags as the system
  3786.              call of the same name.
  3787.  
  3788.      redo LABEL
  3789.  
  3790.      redo    The _r_e_d_o command restarts the loop block without
  3791.              evaluating the conditional again.  The _c_o_n_t_i_n_u_e
  3792.              block, if any, is not executed.  If the LABEL is
  3793.              omitted, the command refers to the innermost enclos-
  3794.              ing loop.  This command is normally used by programs
  3795.              that want to lie to themselves about what was just
  3796.              input:
  3797.  
  3798.                   # a simpleminded Pascal comment stripper
  3799.                   # (warning: assumes no { or } in strings)
  3800.                   line: while (<STDIN>) {
  3801.                        while (s|({.*}.*){.*}|$1 |) {}
  3802.                        s|{.*}| |;
  3803.                        if (s|{.*| |) {
  3804.                             $front = $_;
  3805.                             while (<STDIN>) {
  3806.                                  if (/}/) {     # end of comment?
  3807.                                       s|^|$front{|;
  3808.                                       redo line;
  3809.                                  }
  3810.                             }
  3811.                        }
  3812.                        print;
  3813.                   }
  3814.  
  3815.  
  3816.      rename(OLDNAME,NEWNAME)
  3817.              Changes the name of a file.  Returns 1 for success,
  3818.              0 otherwise.  Will not work across filesystem boun-
  3819.              daries.
  3820.  
  3821.  
  3822.  
  3823.  
  3824.  
  3825. Sprite v1.0                                                    58
  3826.  
  3827.  
  3828.  
  3829.  
  3830.  
  3831.  
  3832. PERL                      User Commands                      PERL
  3833.  
  3834.  
  3835.  
  3836.      require(EXPR)
  3837.  
  3838.      require EXPR
  3839.  
  3840.      require Includes the library file specified by EXPR, or by
  3841.              $_ if EXPR is not supplied.  Has semantics similar
  3842.              to the following subroutine:
  3843.  
  3844.                   sub require {
  3845.                       local($filename) = @_;
  3846.                       return 1 if $INC{$filename};
  3847.                       local($realfilename,$result);
  3848.                       ITER: {
  3849.                        foreach $prefix (@INC) {
  3850.                            $realfilename = "$prefix/$filename";
  3851.                            if (-f $realfilename) {
  3852.                             $result = do $realfilename;
  3853.                             last ITER;
  3854.                            }
  3855.                        }
  3856.                        die "Can't find $filename in \@INC";
  3857.                       }
  3858.                       die $@ if $@;
  3859.                       die "$filename did not return true value" unless $result;
  3860.                       $INC{$filename} = $realfilename;
  3861.                       $result;
  3862.                   }
  3863.  
  3864.              Note that the file will not be included twice under
  3865.              the same specified name.
  3866.  
  3867.      reset(EXPR)
  3868.  
  3869.      reset EXPR
  3870.  
  3871.      reset   Generally used in a _c_o_n_t_i_n_u_e block at the end of a
  3872.              loop to clear variables and reset ?? searches so
  3873.              that they work again.  The expression is interpreted
  3874.              as a list of single characters (hyphens allowed for
  3875.              ranges).  All variables and arrays beginning with
  3876.              one of those letters are reset to their pristine
  3877.              state.  If the expression is omitted, one-match
  3878.              searches (?pattern?) are reset to match again.  Only
  3879.              resets variables or searches in the current package.
  3880.              Always returns 1.  Examples:
  3881.  
  3882.                  reset 'X';      # reset all X variables
  3883.                  reset 'a-z';    # reset lower case variables
  3884.                  reset;          # just reset ?? searches
  3885.  
  3886.              Note: resetting "A-Z" is not recommended since
  3887.              you'll wipe out your ARGV and ENV arrays.
  3888.  
  3889.  
  3890.  
  3891. Sprite v1.0                                                    59
  3892.  
  3893.  
  3894.  
  3895.  
  3896.  
  3897.  
  3898. PERL                      User Commands                      PERL
  3899.  
  3900.  
  3901.  
  3902.              The use of reset on dbm associative arrays does not
  3903.              change the dbm file.  (It does, however, flush any
  3904.              entries cached by perl, which may be useful if you
  3905.              are sharing the dbm file.  Then again, maybe not.)
  3906.  
  3907.      return LIST
  3908.              Returns from a subroutine with the value specified.
  3909.              (Note that a subroutine can automatically return the
  3910.              value of the last expression evaluated.  That's the
  3911.              preferred method--use of an explicit _r_e_t_u_r_n is a bit
  3912.              slower.)
  3913.  
  3914.      reverse(LIST)
  3915.  
  3916.      reverse LIST
  3917.              In an array context, returns an array value consist-
  3918.              ing of the elements of LIST in the opposite order.
  3919.              In a scalar context, returns a string value consist-
  3920.              ing of the bytes of the first element of LIST in the
  3921.              opposite order.
  3922.  
  3923.      rewinddir(DIRHANDLE)
  3924.  
  3925.      rewinddir DIRHANDLE
  3926.              Sets the current position to the beginning of the
  3927.              directory for the readdir() routine on DIRHANDLE.
  3928.  
  3929.      rindex(STR,SUBSTR,POSITION)
  3930.  
  3931.      rindex(STR,SUBSTR)
  3932.              Works just like index except that it returns the
  3933.              position of the LAST occurrence of SUBSTR in STR.
  3934.              If POSITION is specified, returns the last
  3935.              occurrence at or before that position.
  3936.  
  3937.      rmdir(FILENAME)
  3938.  
  3939.      rmdir FILENAME
  3940.              Deletes the directory specified by FILENAME if it is
  3941.              empty.  If it succeeds it returns 1, otherwise it
  3942.              returns 0 and sets $! (errno).  If FILENAME is omit-
  3943.              ted, uses $_.
  3944.  
  3945.      s/PATTERN/REPLACEMENT/gieo
  3946.              Searches a string for a pattern, and if found,
  3947.              replaces that pattern with the replacement text and
  3948.              returns the number of substitutions made.  Otherwise
  3949.              it returns false (0).  The "g" is optional, and if
  3950.              present, indicates that all occurrences of the pat-
  3951.              tern are to be replaced.  The "i" is also optional,
  3952.              and if present, indicates that matching is to be
  3953.              done in a case-insensitive manner.  The "e" is
  3954.  
  3955.  
  3956.  
  3957. Sprite v1.0                                                    60
  3958.  
  3959.  
  3960.  
  3961.  
  3962.  
  3963.  
  3964. PERL                      User Commands                      PERL
  3965.  
  3966.  
  3967.  
  3968.              likewise optional, and if present, indicates that
  3969.              the replacement string is to be evaluated as an
  3970.              expression rather than just as a double-quoted
  3971.              string.  Any non-alphanumeric delimiter may replace
  3972.              the slashes; if single quotes are used, no interpre-
  3973.              tation is done on the replacement string (the e
  3974.              modifier overrides this, however); if backquotes are
  3975.              used, the replacement string is a command to execute
  3976.              whose output will be used as the actual replacement
  3977.              text.  If no string is specified via the =~ or !~
  3978.              operator, the $_ string is searched and modified.
  3979.              (The string specified with =~ must be a scalar vari-
  3980.              able, an array element, or an assignment to one of
  3981.              those, i.e. an lvalue.) If the pattern contains a $
  3982.              that looks like a variable rather than an end-of-
  3983.              string test, the variable will be interpolated into
  3984.              the pattern at run-time.  If you only want the pat-
  3985.              tern compiled once the first time the variable is
  3986.              interpolated, add an "o" at the end.  If the PATTERN
  3987.              evaluates to a null string, the most recent success-
  3988.              ful regular expression is used instead.  See also
  3989.              the section on regular expressions.  Examples:
  3990.  
  3991.                  s/\bgreen\b/mauve/g;      # don't change wintergreen
  3992.  
  3993.                  $path =~ s|/usr/bin|/usr/local/bin|;
  3994.  
  3995.                  s/Login: $foo/Login: $bar/; # run-time pattern
  3996.  
  3997.                  ($foo = $bar) =~ s/bar/foo/;
  3998.  
  3999.                  $_ = 'abc123xyz';
  4000.                  s/\d+/$&*2/e;        # yields 'abc246xyz'
  4001.                  s/\d+/sprintf("%5d",$&)/e;     # yields 'abc  246xyz'
  4002.                  s/\w/$& x 2/eg;      # yields 'aabbcc  224466xxyyzz'
  4003.  
  4004.                  s/([^ ]*) *([^ ]*)/$2 $1/;     # reverse 1st two fields
  4005.  
  4006.              (Note the use of $ instead of \ in the last example.
  4007.              See section on regular expressions.)
  4008.  
  4009.      scalar(EXPR)
  4010.              Forces EXPR to be interpreted in a scalar context
  4011.              and returns the value of EXPR.
  4012.  
  4013.      seek(FILEHANDLE,POSITION,WHENCE)
  4014.              Randomly positions the file pointer for FILEHANDLE,
  4015.              just like the fseek() call of stdio.  FILEHANDLE may
  4016.              be an expression whose value gives the name of the
  4017.              filehandle.  Returns 1 upon success, 0 otherwise.
  4018.  
  4019.  
  4020.  
  4021.  
  4022.  
  4023. Sprite v1.0                                                    61
  4024.  
  4025.  
  4026.  
  4027.  
  4028.  
  4029.  
  4030. PERL                      User Commands                      PERL
  4031.  
  4032.  
  4033.  
  4034.      seekdir(DIRHANDLE,POS)
  4035.              Sets the current position for the readdir() routine
  4036.              on DIRHANDLE.  POS must be a value returned by
  4037.              telldir().  Has the same caveats about possible
  4038.              directory compaction as the corresponding system
  4039.              library routine.
  4040.  
  4041.      select(FILEHANDLE)
  4042.  
  4043.      select  Returns the currently selected filehandle.  Sets the
  4044.              current default filehandle for output, if FILEHANDLE
  4045.              is supplied.  This has two effects: first, a _w_r_i_t_e
  4046.              or a _p_r_i_n_t without a filehandle will default to this
  4047.              FILEHANDLE.  Second, references to variables related
  4048.              to output will refer to this output channel.  For
  4049.              example, if you have to set the top of form format
  4050.              for more than one output channel, you might do the
  4051.              following:
  4052.  
  4053.                   select(REPORT1);
  4054.                   $^ = 'report1_top';
  4055.                   select(REPORT2);
  4056.                   $^ = 'report2_top';
  4057.  
  4058.              FILEHANDLE may be an expression whose value gives
  4059.              the name of the actual filehandle.  Thus:
  4060.  
  4061.                   $oldfh = select(STDERR); $| = 1; select($oldfh);
  4062.  
  4063.  
  4064.      select(RBITS,WBITS,EBITS,TIMEOUT)
  4065.              This calls the select system call with the bitmasks
  4066.              specified, which can be constructed using fileno()
  4067.              and vec(), along these lines:
  4068.  
  4069.                   $rin = $win = $ein = '';
  4070.                   vec($rin,fileno(STDIN),1) = 1;
  4071.                   vec($win,fileno(STDOUT),1) = 1;
  4072.                   $ein = $rin | $win;
  4073.  
  4074.              If you want to select on many filehandles you might
  4075.              wish to write a subroutine:
  4076.  
  4077.                   sub fhbits {
  4078.                       local(@fhlist) = split(' ',$_[0]);
  4079.                       local($bits);
  4080.                       for (@fhlist) {
  4081.                        vec($bits,fileno($_),1) = 1;
  4082.                       }
  4083.                       $bits;
  4084.                   }
  4085.                   $rin = &fhbits('STDIN TTY SOCK');
  4086.  
  4087.  
  4088.  
  4089. Sprite v1.0                                                    62
  4090.  
  4091.  
  4092.  
  4093.  
  4094.  
  4095.  
  4096. PERL                      User Commands                      PERL
  4097.  
  4098.  
  4099.  
  4100.              The usual idiom is:
  4101.  
  4102.                   ($nfound,$timeleft) =
  4103.                     select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  4104.  
  4105.              or to block until something becomes ready:
  4106.  
  4107.                   $nfound = select($rout=$rin, $wout=$win,
  4108.                                  $eout=$ein, undef);
  4109.  
  4110.              Any of the bitmasks can also be undef.  The timeout,
  4111.              if specified, is in seconds, which may be frac-
  4112.              tional.  NOTE: not all implementations are capable
  4113.              of returning the $timeleft.  If not, they always
  4114.              return $timeleft equal to the supplied $timeout.
  4115.  
  4116.      semctl(ID,SEMNUM,CMD,ARG)
  4117.              Calls the System V IPC function semctl.  If CMD is
  4118.              &IPC_STAT or &GETALL, then ARG must be a variable
  4119.              which will hold the returned semid_ds structure or
  4120.              semaphore value array.  Returns like ioctl: the
  4121.              undefined value for error, "0 but true" for zero, or
  4122.              the actual return value otherwise.
  4123.  
  4124.      semget(KEY,NSEMS,SIZE,FLAGS)
  4125.              Calls the System V IPC function semget.  Returns the
  4126.              semaphore id, or the undefined value if there is an
  4127.              error.
  4128.  
  4129.      semop(KEY,OPSTRING)
  4130.              Calls the System V IPC function semop to perform
  4131.              semaphore operations such as signaling and waiting.
  4132.              OPSTRING must be a packed array of semop structures.
  4133.              Each semop structure can be generated with
  4134.              'pack("sss", $semnum, $semop, $semflag)'.  The
  4135.              number of semaphore operations is implied by the
  4136.              length of OPSTRING.  Returns true if successful, or
  4137.              false if there is an error.  As an example, the fol-
  4138.              lowing code waits on semaphore $semnum of semaphore
  4139.              id $semid:
  4140.  
  4141.                   $semop = pack("sss", $semnum, -1, 0);
  4142.                   die "Semaphore trouble: $!\n" unless semop($semid, $semop);
  4143.  
  4144.              To signal the semaphore, replace "-1" with "1".
  4145.  
  4146.      send(SOCKET,MSG,FLAGS,TO)
  4147.  
  4148.      send(SOCKET,MSG,FLAGS)
  4149.              Sends a message on a socket.  Takes the same flags
  4150.              as the system call of the same name.  On unconnected
  4151.              sockets you must specify a destination to send TO.
  4152.  
  4153.  
  4154.  
  4155. Sprite v1.0                                                    63
  4156.  
  4157.  
  4158.  
  4159.  
  4160.  
  4161.  
  4162. PERL                      User Commands                      PERL
  4163.  
  4164.  
  4165.  
  4166.              Returns the number of characters sent, or the unde-
  4167.              fined value if there is an error.
  4168.  
  4169.      setpgrp(PID,PGRP)
  4170.              Sets the current process group for the specified
  4171.              PID, 0 for the current process.  Will produce a
  4172.              fatal error if used on a machine that doesn't imple-
  4173.              ment setpgrp(2).
  4174.  
  4175.      setpriority(WHICH,WHO,PRIORITY)
  4176.              Sets the current priority for a process, a process
  4177.              group, or a user.  (See setpriority(2).) Will pro-
  4178.              duce a fatal error if used on a machine that doesn't
  4179.              implement setpriority(2).
  4180.  
  4181.      setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
  4182.              Sets the socket option requested.  Returns undefined
  4183.              if there is an error.  OPTVAL may be specified as
  4184.              undef if you don't want to pass an argument.
  4185.  
  4186.      shift(ARRAY)
  4187.  
  4188.      shift ARRAY
  4189.  
  4190.      shift   Shifts the first value of the array off and returns
  4191.              it, shortening the array by 1 and moving everything
  4192.              down.  If there are no elements in the array,
  4193.              returns the undefined value.  If ARRAY is omitted,
  4194.              shifts the @ARGV array in the main program, and the
  4195.              @_ array in subroutines.  (This is determined lexi-
  4196.              cally.) See also unshift(), push() and pop().
  4197.              Shift() and unshift() do the same thing to the left
  4198.              end of an array that push() and pop() do to the
  4199.              right end.
  4200.  
  4201.      shmctl(ID,CMD,ARG)
  4202.              Calls the System V IPC function shmctl.  If CMD is
  4203.              &IPC_STAT, then ARG must be a variable which will
  4204.              hold the returned shmid_ds structure.  Returns like
  4205.              ioctl: the undefined value for error, "0 but true"
  4206.              for zero, or the actual return value otherwise.
  4207.  
  4208.      shmget(KEY,SIZE,FLAGS)
  4209.              Calls the System V IPC function shmget.  Returns the
  4210.              shared memory segment id, or the undefined value if
  4211.              there is an error.
  4212.  
  4213.      shmread(ID,VAR,POS,SIZE)
  4214.  
  4215.      shmwrite(ID,STRING,POS,SIZE)
  4216.              Reads or writes the System V shared memory segment
  4217.              ID starting at position POS for size SIZE by
  4218.  
  4219.  
  4220.  
  4221. Sprite v1.0                                                    64
  4222.  
  4223.  
  4224.  
  4225.  
  4226.  
  4227.  
  4228. PERL                      User Commands                      PERL
  4229.  
  4230.  
  4231.  
  4232.              attaching to it, copying in/out, and detaching from
  4233.              it.  When reading, VAR must be a variable which will
  4234.              hold the data read.  When writing, if STRING is too
  4235.              long, only SIZE bytes are used; if STRING is too
  4236.              short, nulls are written to fill out SIZE bytes.
  4237.              Return true if successful, or false if there is an
  4238.              error.
  4239.  
  4240.      shutdown(SOCKET,HOW)
  4241.              Shuts down a socket connection in the manner indi-
  4242.              cated by HOW, which has the same interpretation as
  4243.              in the system call of the same name.
  4244.  
  4245.      sin(EXPR)
  4246.  
  4247.      sin EXPR
  4248.              Returns the sine of EXPR (expressed in radians).  If
  4249.              EXPR is omitted, returns sine of $_.
  4250.  
  4251.      sleep(EXPR)
  4252.  
  4253.      sleep EXPR
  4254.  
  4255.      sleep   Causes the script to sleep for EXPR seconds, or for-
  4256.              ever if no EXPR.  May be interrupted by sending the
  4257.              process a SIGALRM.  Returns the number of seconds
  4258.              actually slept.  You probably cannot mix alarm() and
  4259.              sleep() calls, since sleep() is often implemented
  4260.              using alarm().
  4261.  
  4262.      socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
  4263.              Opens a socket of the specified kind and attaches it
  4264.              to filehandle SOCKET.  DOMAIN, TYPE and PROTOCOL are
  4265.              specified the same as for the system call of the
  4266.              same name.  You may need to run h2ph on sys/socket.h
  4267.              to get the proper values handy in a perl library
  4268.              file.  Return true if successful.  See the example
  4269.              in the section on Interprocess Communication.
  4270.  
  4271.      socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
  4272.              Creates an unnamed pair of sockets in the specified
  4273.              domain, of the specified type.  DOMAIN, TYPE and
  4274.              PROTOCOL are specified the same as for the system
  4275.              call of the same name.  If unimplemented, yields a
  4276.              fatal error.  Return true if successful.
  4277.  
  4278.  
  4279.  
  4280.  
  4281.  
  4282.  
  4283.  
  4284.  
  4285.  
  4286.  
  4287. Sprite v1.0                                                    65
  4288.  
  4289.  
  4290.  
  4291.  
  4292.  
  4293.  
  4294. PERL                      User Commands                      PERL
  4295.  
  4296.  
  4297.  
  4298.      sort(SUBROUTINE LIST)
  4299.  
  4300.      sort(LIST)
  4301.  
  4302.      sort SUBROUTINE LIST
  4303.  
  4304.      sort BLOCK LIST
  4305.  
  4306.      sort LIST
  4307.              Sorts the LIST and returns the sorted array value.
  4308.              Nonexistent values of arrays are stripped out.  If
  4309.              SUBROUTINE or BLOCK is omitted, sorts in standard
  4310.              string comparison order.  If SUBROUTINE is speci-
  4311.              fied, gives the name of a subroutine that returns an
  4312.              integer less than, equal to, or greater than 0,
  4313.              depending on how the elements of the array are to be
  4314.              ordered.  (The <=> and cmp operators are extremely
  4315.              useful in such routines.) SUBROUTINE may be a scalar
  4316.              variable name, in which case the value provides the
  4317.              name of the subroutine to use.  In place of a SUB-
  4318.              ROUTINE name, you can provide a BLOCK as an
  4319.              anonymous, in-line sort subroutine.
  4320.  
  4321.              In the interests of efficiency the normal calling
  4322.              code for subroutines is bypassed, with the following
  4323.              effects: the subroutine may not be a recursive sub-
  4324.              routine, and the two elements to be compared are
  4325.              passed into the subroutine not via @_ but as $a and
  4326.              $b (see example below).  They are passed by refer-
  4327.              ence so don't modify $a and $b.
  4328.  
  4329.              Examples:
  4330.  
  4331.                   # sort lexically
  4332.                   @articles = sort @files;
  4333.  
  4334.                   # same thing, but with explicit sort routine
  4335.                   @articles = sort {$a cmp $b;} @files;
  4336.  
  4337.                   # same thing in reversed order
  4338.                   @articles = sort {$b cmp $a;} @files;
  4339.  
  4340.                   # sort numerically ascending
  4341.                   @articles = sort {$a <=> $b;} @files;
  4342.  
  4343.                   # sort numerically descending
  4344.                   @articles = sort {$b <=> $a;} @files;
  4345.  
  4346.  
  4347.  
  4348.  
  4349.  
  4350.  
  4351.  
  4352.  
  4353. Sprite v1.0                                                    66
  4354.  
  4355.  
  4356.  
  4357.  
  4358.  
  4359.  
  4360. PERL                      User Commands                      PERL
  4361.  
  4362.  
  4363.  
  4364.                   # sort using explicit subroutine name
  4365.                   sub byage {
  4366.                       $age{$a} <=> $age{$b};    # presuming integers
  4367.                   }
  4368.                   @sortedclass = sort byage @class;
  4369.  
  4370.                   sub reverse { $b cmp $a; }
  4371.                   @harry = ('dog','cat','x','Cain','Abel');
  4372.                   @george = ('gone','chased','yz','Punished','Axed');
  4373.                   print sort @harry;
  4374.                        # prints AbelCaincatdogx
  4375.                   print sort reverse @harry;
  4376.                        # prints xdogcatCainAbel
  4377.                   print sort @george, 'to', @harry;
  4378.                        # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  4379.  
  4380.  
  4381.      splice(ARRAY,OFFSET,LENGTH,LIST)
  4382.  
  4383.      splice(ARRAY,OFFSET,LENGTH)
  4384.  
  4385.      splice(ARRAY,OFFSET)
  4386.              Removes the elements designated by OFFSET and LENGTH
  4387.              from an array, and replaces them with the elements
  4388.              of LIST, if any.  Returns the elements removed from
  4389.              the array.  The array grows or shrinks as necessary.
  4390.              If LENGTH is omitted, removes everything from OFFSET
  4391.              onward.  The following equivalencies hold (assuming
  4392.              $[ == 0):
  4393.  
  4394.                   push(@a,$x,$y)                splice(@a,$#a+1,0,$x,$y)
  4395.                   pop(@a)                       splice(@a,-1)
  4396.                   shift(@a)                     splice(@a,0,1)
  4397.                   unshift(@a,$x,$y)             splice(@a,0,0,$x,$y)
  4398.                   $a[$x] = $y                   splice(@a,$x,1,$y);
  4399.  
  4400.              Example, assuming array lengths are passed before arrays:
  4401.  
  4402.                   sub aeq { # compare two array values
  4403.                        local(@a) = splice(@_,0,shift);
  4404.                        local(@b) = splice(@_,0,shift);
  4405.                        return 0 unless @a == @b;     # same len?
  4406.                        while (@a) {
  4407.                            return 0 if pop(@a) ne pop(@b);
  4408.                        }
  4409.                        return 1;
  4410.                   }
  4411.                   if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  4412.  
  4413.  
  4414.  
  4415.  
  4416.  
  4417.  
  4418.  
  4419. Sprite v1.0                                                    67
  4420.  
  4421.  
  4422.  
  4423.  
  4424.  
  4425.  
  4426. PERL                      User Commands                      PERL
  4427.  
  4428.  
  4429.  
  4430.      split(/PATTERN/,EXPR,LIMIT)
  4431.  
  4432.      split(/PATTERN/,EXPR)
  4433.  
  4434.      split(/PATTERN/)
  4435.  
  4436.      split   Splits a string into an array of strings, and
  4437.              returns it.  (If not in an array context, returns
  4438.              the number of fields found and splits into the @_
  4439.              array.  (In an array context, you can force the
  4440.              split into @_ by using ?? as the pattern delimiters,
  4441.              but it still returns the array value.)) If EXPR is
  4442.              omitted, splits the $_ string.  If PATTERN is also
  4443.              omitted, splits on whitespace (/[ \t\n]+/).  Any-
  4444.              thing matching PATTERN is taken to be a delimiter
  4445.              separating the fields.  (Note that the delimiter may
  4446.              be longer than one character.) If LIMIT is speci-
  4447.              fied, splits into no more than that many fields
  4448.              (though it may split into fewer).  If LIMIT is
  4449.              unspecified, trailing null fields are stripped
  4450.              (which potential users of pop() would do well to
  4451.              remember).  A pattern matching the null string (not
  4452.              to be confused with a null pattern //, which is just
  4453.              one member of the set of patterns matching a null
  4454.              string) will split the value of EXPR into separate
  4455.              characters at each point it matches that way.  For
  4456.              example:
  4457.  
  4458.                   print join(':', split(/ */, 'hi there'));
  4459.  
  4460.              produces the output 'h:i:t:h:e:r:e'.
  4461.  
  4462.              The LIMIT parameter can be used to partially split a
  4463.              line
  4464.  
  4465.                   ($login, $passwd, $remainder) = split(/:/, $_, 3);
  4466.  
  4467.              (When assigning to a list, if LIMIT is omitted, perl
  4468.              supplies a LIMIT one larger than the number of vari-
  4469.              ables in the list, to avoid unnecessary work.  For
  4470.              the list above LIMIT would have been 4 by default.
  4471.              In time critical applications it behooves you not to
  4472.              split into more fields than you really need.)
  4473.  
  4474.              If the PATTERN contains parentheses, additional
  4475.              array elements are created from each matching sub-
  4476.              string in the delimiter.
  4477.  
  4478.                   split(/([,-])/,"1-10,20");
  4479.  
  4480.              produces the array value
  4481.  
  4482.  
  4483.  
  4484.  
  4485. Sprite v1.0                                                    68
  4486.  
  4487.  
  4488.  
  4489.  
  4490.  
  4491.  
  4492. PERL                      User Commands                      PERL
  4493.  
  4494.  
  4495.  
  4496.                   (1,'-',10,',',20)
  4497.  
  4498.              The pattern /PATTERN/ may be replaced with an
  4499.              expression to specify patterns that vary at runtime.
  4500.              (To do runtime compilation only once, use
  4501.              /$variable/o.) As a special case, specifying a space
  4502.              (' ') will split on white space just as split with
  4503.              no arguments does, but leading white space does NOT
  4504.              produce a null first field.  Thus, split(' ') can be
  4505.              used to emulate _a_w_k's default behavior, whereas
  4506.              split(/ /) will give you as many null initial fields
  4507.              as there are leading spaces.
  4508.  
  4509.              Example:
  4510.  
  4511.                   open(passwd, '/etc/passwd');
  4512.                   while (<passwd>) {
  4513.                        ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  4514.                             = split(/:/);
  4515.                        ...
  4516.                   }
  4517.  
  4518.              (Note that $shell above will still have a newline on
  4519.              it.  See chop().) See also _j_o_i_n.
  4520.  
  4521.      sprintf(FORMAT,LIST)
  4522.              Returns a string formatted by the usual printf con-
  4523.              ventions.  The * character is not supported.
  4524.  
  4525.      sqrt(EXPR)
  4526.  
  4527.      sqrt EXPR
  4528.              Return the square root of EXPR.  If EXPR is omitted,
  4529.              returns square root of $_.
  4530.  
  4531.      srand(EXPR)
  4532.  
  4533.      srand EXPR
  4534.              Sets the random number seed for the _r_a_n_d operator.
  4535.              If EXPR is omitted, does srand(time).
  4536.  
  4537.      stat(FILEHANDLE)
  4538.  
  4539.      stat FILEHANDLE
  4540.  
  4541.      stat(EXPR)
  4542.  
  4543.      stat SCALARVARIABLE
  4544.              Returns a 13-element array giving the statistics for
  4545.              a file, either the file opened via FILEHANDLE, or
  4546.              named by EXPR.  Typically used as follows:
  4547.  
  4548.  
  4549.  
  4550.  
  4551. Sprite v1.0                                                    69
  4552.  
  4553.  
  4554.  
  4555.  
  4556.  
  4557.  
  4558. PERL                      User Commands                      PERL
  4559.  
  4560.  
  4561.  
  4562.                  ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  4563.                     $atime,$mtime,$ctime,$blksize,$blocks)
  4564.                         = stat($filename);
  4565.  
  4566.              If stat is passed the special filehandle consisting
  4567.              of an underline, no stat is done, but the current
  4568.              contents of the stat structure from the last stat or
  4569.              filetest are returned.  Example:
  4570.  
  4571.                   if (-x $file && (($d) = stat(_)) && $d < 0) {
  4572.                        print "$file is executable NFS file\n";
  4573.                   }
  4574.  
  4575.              (This only works on machines for which the device
  4576.              number is negative under NFS.)
  4577.  
  4578.      study(SCALAR)
  4579.  
  4580.      study SCALAR
  4581.  
  4582.      study   Takes extra time to study SCALAR ($_ if unspecified)
  4583.              in anticipation of doing many pattern matches on the
  4584.              string before it is next modified.  This may or may
  4585.              not save time, depending on the nature and number of
  4586.              patterns you are searching on, and on the distribu-
  4587.              tion of character frequencies in the string to be
  4588.              searched--you probably want to compare runtimes with
  4589.              and without it to see which runs faster.  Those
  4590.              loops which scan for many short constant strings
  4591.              (including the constant parts of more complex pat-
  4592.              terns) will benefit most.  You may have only one
  4593.              study active at a time--if you study a different
  4594.              scalar the first is "unstudied".  (The way study
  4595.              works is this: a linked list of every character in
  4596.              the string to be searched is made, so we know, for
  4597.              example, where all the 'k' characters are.  From
  4598.              each search string, the rarest character is
  4599.              selected, based on some static frequency tables con-
  4600.              structed from some C programs and English text.
  4601.              Only those places that contain this "rarest" charac-
  4602.              ter are examined.)
  4603.  
  4604.              For example, here is a loop which inserts index pro-
  4605.              ducing entries before any line containing a certain
  4606.              pattern:
  4607.  
  4608.  
  4609.  
  4610.  
  4611.  
  4612.  
  4613.  
  4614.  
  4615.  
  4616.  
  4617. Sprite v1.0                                                    70
  4618.  
  4619.  
  4620.  
  4621.  
  4622.  
  4623.  
  4624. PERL                      User Commands                      PERL
  4625.  
  4626.  
  4627.  
  4628.                   while (<>) {
  4629.                        study;
  4630.                        print ".IX foo\n" if /\bfoo\b/;
  4631.                        print ".IX bar\n" if /\bbar\b/;
  4632.                        print ".IX blurfl\n" if /\bblurfl\b/;
  4633.                        ...
  4634.                        print;
  4635.                   }
  4636.  
  4637.              In searching for /\bfoo\b/, only those locations in
  4638.              $_ that contain 'f' will be looked at, because 'f'
  4639.              is rarer than 'o'.  In general, this is a big win
  4640.              except in pathological cases.  The only question is
  4641.              whether it saves you more time than it took to build
  4642.              the linked list in the first place.
  4643.  
  4644.              Note that if you have to look for strings that you
  4645.              don't know till runtime, you can build an entire
  4646.              loop as a string and eval that to avoid recompiling
  4647.              all your patterns all the time.  Together with unde-
  4648.              fining $/ to input entire files as one record, this
  4649.              can be very fast, often faster than specialized pro-
  4650.              grams like fgrep.  The following scans a list of
  4651.              files (@files) for a list of words (@words), and
  4652.              prints out the names of those files that contain a
  4653.              match:
  4654.  
  4655.                   $search = 'while (<>) { study;';
  4656.                   foreach $word (@words) {
  4657.                       $search .= "++\$seen{\$ARGV} if /\b$word\b/;\n";
  4658.                   }
  4659.                   $search .= "}";
  4660.                   @ARGV = @files;
  4661.                   undef $/;
  4662.                   eval $search;       # this screams
  4663.                   $/ = "\n";          # put back to normal input delim
  4664.                   foreach $file (sort keys(%seen)) {
  4665.                       print $file, "\n";
  4666.                   }
  4667.  
  4668.  
  4669.      substr(EXPR,OFFSET,LEN)
  4670.  
  4671.      substr(EXPR,OFFSET)
  4672.              Extracts a substring out of EXPR and returns it.
  4673.              First character is at offset 0, or whatever you've
  4674.              set $[ to.  If OFFSET is negative, starts that far
  4675.              from the end of the string.  If LEN is omitted,
  4676.              returns everything to the end of the string.  You
  4677.              can use the substr() function as an lvalue, in which
  4678.              case EXPR must be an lvalue.  If you assign some-
  4679.              thing shorter than LEN, the string will shrink, and
  4680.  
  4681.  
  4682.  
  4683. Sprite v1.0                                                    71
  4684.  
  4685.  
  4686.  
  4687.  
  4688.  
  4689.  
  4690. PERL                      User Commands                      PERL
  4691.  
  4692.  
  4693.  
  4694.              if you assign something longer than LEN, the string
  4695.              will grow to accommodate it.  To keep the string the
  4696.              same length you may need to pad or chop your value
  4697.              using sprintf().
  4698.  
  4699.      symlink(OLDFILE,NEWFILE)
  4700.              Creates a new filename symbolically linked to the
  4701.              old filename.  Returns 1 for success, 0 otherwise.
  4702.              On systems that don't support symbolic links, pro-
  4703.              duces a fatal error at run time.  To check for that,
  4704.              use eval:
  4705.  
  4706.                   $symlink_exists = (eval 'symlink("","");', $@ eq '');
  4707.  
  4708.  
  4709.      syscall(LIST)
  4710.  
  4711.      syscall LIST
  4712.              Calls the system call specified as the first element
  4713.              of the list, passing the remaining elements as argu-
  4714.              ments to the system call.  If unimplemented, pro-
  4715.              duces a fatal error.  The arguments are interpreted
  4716.              as follows: if a given argument is numeric, the
  4717.              argument is passed as an int.  If not, the pointer
  4718.              to the string value is passed.  You are responsible
  4719.              to make sure a string is pre-extended long enough to
  4720.              receive any result that might be written into a
  4721.              string.  If your integer arguments are not literals
  4722.              and have never been interpreted in a numeric con-
  4723.              text, you may need to add 0 to them to force them to
  4724.              look like numbers.
  4725.  
  4726.                   require 'syscall.ph';         # may need to run h2ph
  4727.                   syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);
  4728.  
  4729.  
  4730.      sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  4731.  
  4732.      sysread(FILEHANDLE,SCALAR,LENGTH)
  4733.              Attempts to read LENGTH bytes of data into variable
  4734.              SCALAR from the specified FILEHANDLE, using the sys-
  4735.              tem call read(2).  It bypasses stdio, so mixing this
  4736.              with other kinds of reads may cause confusion.
  4737.              Returns the number of bytes actually read, or undef
  4738.              if there was an error.  SCALAR will be grown or
  4739.              shrunk to the length actually read.  An OFFSET may
  4740.              be specified to place the read data at some other
  4741.              place than the beginning of the string.
  4742.  
  4743.  
  4744.  
  4745.  
  4746.  
  4747.  
  4748.  
  4749. Sprite v1.0                                                    72
  4750.  
  4751.  
  4752.  
  4753.  
  4754.  
  4755.  
  4756. PERL                      User Commands                      PERL
  4757.  
  4758.  
  4759.  
  4760.      system(LIST)
  4761.  
  4762.      system LIST
  4763.              Does exactly the same thing as "exec LIST" except
  4764.              that a fork is done first, and the parent process
  4765.              waits for the child process to complete.  Note that
  4766.              argument processing varies depending on the number
  4767.              of arguments.  The return value is the exit status
  4768.              of the program as returned by the wait() call.  To
  4769.              get the actual exit value divide by 256.  See also
  4770.              _e_x_e_c.
  4771.  
  4772.      syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  4773.  
  4774.      syswrite(FILEHANDLE,SCALAR,LENGTH)
  4775.              Attempts to write LENGTH bytes of data from variable
  4776.              SCALAR to the specified FILEHANDLE, using the system
  4777.              call write(2).  It bypasses stdio, so mixing this
  4778.              with prints may cause confusion.  Returns the number
  4779.              of bytes actually written, or undef if there was an
  4780.              error.  An OFFSET may be specified to place the read
  4781.              data at some other place than the beginning of the
  4782.              string.
  4783.  
  4784.      tell(FILEHANDLE)
  4785.  
  4786.      tell FILEHANDLE
  4787.  
  4788.      tell    Returns the current file position for FILEHANDLE.
  4789.              FILEHANDLE may be an expression whose value gives
  4790.              the name of the actual filehandle.  If FILEHANDLE is
  4791.              omitted, assumes the file last read.
  4792.  
  4793.      telldir(DIRHANDLE)
  4794.  
  4795.      telldir DIRHANDLE
  4796.              Returns the current position of the readdir() rou-
  4797.              tines on DIRHANDLE.  Value may be given to seekdir()
  4798.              to access a particular location in a directory.  Has
  4799.              the same caveats about possible directory compaction
  4800.              as the corresponding system library routine.
  4801.  
  4802.      time    Returns the number of non-leap seconds since
  4803.              00:00:00 UTC, January 1, 1970.  Suitable for feeding
  4804.              to gmtime() and localtime().
  4805.  
  4806.      times   Returns a four-element array giving the user and
  4807.              system times, in seconds, for this process and the
  4808.              children of this process.
  4809.  
  4810.                  ($user,$system,$cuser,$csystem) = times;
  4811.  
  4812.  
  4813.  
  4814.  
  4815. Sprite v1.0                                                    73
  4816.  
  4817.  
  4818.  
  4819.  
  4820.  
  4821.  
  4822. PERL                      User Commands                      PERL
  4823.  
  4824.  
  4825.  
  4826.      tr/SEARCHLIST/REPLACEMENTLIST/cds
  4827.  
  4828.      y/SEARCHLIST/REPLACEMENTLIST/cds
  4829.              Translates all occurrences of the characters found
  4830.              in the search list with the corresponding character
  4831.              in the replacement list.  It returns the number of
  4832.              characters replaced or deleted.  If no string is
  4833.              specified via the =~ or !~ operator, the $_ string
  4834.              is translated.  (The string specified with =~ must
  4835.              be a scalar variable, an array element, or an
  4836.              assignment to one of those, i.e. an lvalue.) For _s_e_d
  4837.              devotees, _y is provided as a synonym for _t_r.
  4838.  
  4839.              If the c modifier is specified, the SEARCHLIST char-
  4840.              acter set is complemented.  If the d modifier is
  4841.              specified, any characters specified by SEARCHLIST
  4842.              that are not found in REPLACEMENTLIST are deleted.
  4843.              (Note that this is slightly more flexible than the
  4844.              behavior of some _t_r programs, which delete anything
  4845.              they find in the SEARCHLIST, period.) If the s
  4846.              modifier is specified, sequences of characters that
  4847.              were translated to the same character are squashed
  4848.              down to 1 instance of the character.
  4849.  
  4850.              If the d modifier was used, the REPLACEMENTLIST is
  4851.              always interpreted exactly as specified.  Otherwise,
  4852.              if the REPLACEMENTLIST is shorter than the SEAR-
  4853.              CHLIST, the final character is replicated till it is
  4854.              long enough.  If the REPLACEMENTLIST is null, the
  4855.              SEARCHLIST is replicated.  This latter is useful for
  4856.              counting characters in a class, or for squashing
  4857.              character sequences in a class.
  4858.  
  4859.              Examples:
  4860.  
  4861.                  $ARGV[1] =~ y/A-Z/a-z/;   # canonicalize to lower case
  4862.  
  4863.                  $cnt = tr/*/*/;           # count the stars in $_
  4864.  
  4865.                  $cnt = tr/0-9//;          # count the digits in $_
  4866.  
  4867.                  tr/a-zA-Z//s;             # bookkeeper -> bokeper
  4868.  
  4869.                  ($HOST = $host) =~ tr/a-z/A-Z/;
  4870.  
  4871.                  y/a-zA-Z/ /cs;            # change non-alphas to single space
  4872.  
  4873.                  tr/\200-\377/\0-\177/;    # delete 8th bit
  4874.  
  4875.  
  4876.  
  4877.  
  4878.  
  4879.  
  4880.  
  4881. Sprite v1.0                                                    74
  4882.  
  4883.  
  4884.  
  4885.  
  4886.  
  4887.  
  4888. PERL                      User Commands                      PERL
  4889.  
  4890.  
  4891.  
  4892.      truncate(FILEHANDLE,LENGTH)
  4893.  
  4894.      truncate(EXPR,LENGTH)
  4895.              Truncates the file opened on FILEHANDLE, or named by
  4896.              EXPR, to the specified length.  Produces a fatal
  4897.              error if truncate isn't implemented on your system.
  4898.  
  4899.      umask(EXPR)
  4900.  
  4901.      umask EXPR
  4902.  
  4903.      umask   Sets the umask for the process and returns the old
  4904.              one.  If EXPR is omitted, merely returns current
  4905.              umask.
  4906.  
  4907.      undef(EXPR)
  4908.  
  4909.      undef EXPR
  4910.  
  4911.      undef   Undefines the value of EXPR, which must be an
  4912.              lvalue.  Use only on a scalar value, an entire
  4913.              array, or a subroutine name (using &).  (Undef will
  4914.              probably not do what you expect on most predefined
  4915.              variables or dbm array values.) Always returns the
  4916.              undefined value.  You can omit the EXPR, in which
  4917.              case nothing is undefined, but you still get an
  4918.              undefined value that you could, for instance, return
  4919.              from a subroutine.  Examples:
  4920.  
  4921.                   undef $foo;
  4922.                   undef $bar{'blurfl'};
  4923.                   undef @ary;
  4924.                   undef %assoc;
  4925.                   undef &mysub;
  4926.                   return (wantarray ? () : undef) if $they_blew_it;
  4927.  
  4928.  
  4929.      unlink(LIST)
  4930.  
  4931.      unlink LIST
  4932.              Deletes a list of files.  Returns the number of
  4933.              files successfully deleted.
  4934.  
  4935.                   $cnt = unlink 'a', 'b', 'c';
  4936.                   unlink @goners;
  4937.                   unlink <*.bak>;
  4938.  
  4939.              Note: unlink will not delete directories unless you
  4940.              are superuser and the --UU flag is supplied to _p_e_r_l.
  4941.              Even if these conditions are met, be warned that
  4942.              unlinking a directory can inflict damage on your
  4943.              filesystem.  Use rmdir instead.
  4944.  
  4945.  
  4946.  
  4947. Sprite v1.0                                                    75
  4948.  
  4949.  
  4950.  
  4951.  
  4952.  
  4953.  
  4954. PERL                      User Commands                      PERL
  4955.  
  4956.  
  4957.  
  4958.      unpack(TEMPLATE,EXPR)
  4959.              Unpack does the reverse of pack: it takes a string
  4960.              representing a structure and expands it out into an
  4961.              array value, returning the array value.  (In a
  4962.              scalar context, it merely returns the first value
  4963.              produced.) The TEMPLATE has the same format as in
  4964.              the pack function.  Here's a subroutine that does
  4965.              substring:
  4966.  
  4967.                   sub substr {
  4968.                        local($what,$where,$howmuch) = @_;
  4969.                        unpack("x$where a$howmuch", $what);
  4970.                   }
  4971.  
  4972.              and then there's
  4973.  
  4974.                   sub ord { unpack("c",$_[0]); }
  4975.  
  4976.              In addition, you may prefix a field with a %<number>
  4977.              to indicate that you want a <number>-bit checksum of
  4978.              the items instead of the items themselves.  Default
  4979.              is a 16-bit checksum.  For example, the following
  4980.              computes the same number as the System V sum pro-
  4981.              gram:
  4982.  
  4983.                   while (<>) {
  4984.                       $checksum += unpack("%16C*", $_);
  4985.                   }
  4986.                   $checksum %= 65536;
  4987.  
  4988.  
  4989.      unshift(ARRAY,LIST)
  4990.              Does the opposite of a _s_h_i_f_t.  Or the opposite of a
  4991.              _p_u_s_h, depending on how you look at it.  Prepends
  4992.              list to the front of the array, and returns the
  4993.              number of elements in the new array.
  4994.  
  4995.                   unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
  4996.  
  4997.  
  4998.      utime(LIST)
  4999.  
  5000.      utime LIST
  5001.              Changes the access and modification times on each
  5002.              file of a list of files.  The first two elements of
  5003.              the list must be the NUMERICAL access and modifica-
  5004.              tion times, in that order.  Returns the number of
  5005.              files successfully changed.  The inode modification
  5006.              time of each file is set to the current time.  Exam-
  5007.              ple of a "touch" command:
  5008.  
  5009.  
  5010.  
  5011.  
  5012.  
  5013. Sprite v1.0                                                    76
  5014.  
  5015.  
  5016.  
  5017.  
  5018.  
  5019.  
  5020. PERL                      User Commands                      PERL
  5021.  
  5022.  
  5023.  
  5024.                   #!/usr/bin/perl
  5025.                   $now = time;
  5026.                   utime $now, $now, @ARGV;
  5027.  
  5028.  
  5029.      values(ASSOC_ARRAY)
  5030.  
  5031.      values ASSOC_ARRAY
  5032.              Returns a normal array consisting of all the values
  5033.              of the named associative array.  The values are
  5034.              returned in an apparently random order, but it is
  5035.              the same order as either the keys() or each() func-
  5036.              tion would produce on the same array.  See also
  5037.              keys() and each().
  5038.  
  5039.      vec(EXPR,OFFSET,BITS)
  5040.              Treats a string as a vector of unsigned integers,
  5041.              and returns the value of the bitfield specified.
  5042.              May also be assigned to.  BITS must be a power of
  5043.              two from 1 to 32.
  5044.  
  5045.              Vectors created with vec() can also be manipulated
  5046.              with the logical operators |, & and ^, which will
  5047.              assume a bit vector operation is desired when both
  5048.              operands are strings.  This interpretation is not
  5049.              enabled unless there is at least one vec() in your
  5050.              program, to protect older programs.
  5051.  
  5052.              To transform a bit vector into a string or array of
  5053.              0's and 1's, use these:
  5054.  
  5055.                   $bits = unpack("b*", $vector);
  5056.                   @bits = split(//, unpack("b*", $vector));
  5057.  
  5058.              If you know the exact length in bits, it can be used
  5059.              in place of the *.
  5060.  
  5061.      wait    Waits for a child process to terminate and returns
  5062.              the pid of the deceased process, or -1 if there are
  5063.              no child processes.  The status is returned in $?.
  5064.  
  5065.      waitpid(PID,FLAGS)
  5066.              Waits for a particular child process to terminate
  5067.              and returns the pid of the deceased process, or -1
  5068.              if there is no such child process.  The status is
  5069.              returned in $?.  If you say
  5070.  
  5071.                   require "sys/wait.h";
  5072.                   ...
  5073.                   waitpid(-1,&WNOHANG);
  5074.  
  5075.              then you can do a non-blocking wait for any process.
  5076.  
  5077.  
  5078.  
  5079. Sprite v1.0                                                    77
  5080.  
  5081.  
  5082.  
  5083.  
  5084.  
  5085.  
  5086. PERL                      User Commands                      PERL
  5087.  
  5088.  
  5089.  
  5090.              Non-blocking wait is only available on machines sup-
  5091.              porting either the _w_a_i_t_p_i_d (_2) or _w_a_i_t_4 (_2) system
  5092.              calls.  However, waiting for a particular pid with
  5093.              FLAGS of 0 is implemented everywhere.  (Perl emu-
  5094.              lates the system call by remembering the status
  5095.              values of processes that have exited but have not
  5096.              been harvested by the Perl script yet.)
  5097.  
  5098.      wantarray
  5099.              Returns true if the context of the currently execut-
  5100.              ing subroutine is looking for an array value.
  5101.              Returns false if the context is looking for a
  5102.              scalar.
  5103.  
  5104.                   return wantarray ? () : undef;
  5105.  
  5106.  
  5107.      warn(LIST)
  5108.  
  5109.      warn LIST
  5110.              Produces a message on STDERR just like "die", but
  5111.              doesn't exit.
  5112.  
  5113.      write(FILEHANDLE)
  5114.  
  5115.      write(EXPR)
  5116.  
  5117.      write   Writes a formatted record (possibly multi-line) to
  5118.              the specified file, using the format associated with
  5119.              that file.  By default the format for a file is the
  5120.              one having the same name is the filehandle, but the
  5121.              format for the current output channel (see _s_e_l_e_c_t)
  5122.              may be set explicitly by assigning the name of the
  5123.              format to the $~ variable.
  5124.  
  5125.              Top of form processing is handled automatically: if
  5126.              there is insufficient room on the current page for
  5127.              the formatted record, the page is advanced by writ-
  5128.              ing a form feed, a special top-of-page format is
  5129.              used to format the new page header, and then the
  5130.              record is written.  By default the top-of-page for-
  5131.              mat is the name of the filehandle with "_TOP"
  5132.              appended, but it may be dynamicallly set to the for-
  5133.              mat of your choice by assigning the name to the $^
  5134.              variable while the filehandle is selected.  The
  5135.              number of lines remaining on the current page is in
  5136.              variable $-, which can be set to 0 to force a new
  5137.              page.
  5138.  
  5139.              If FILEHANDLE is unspecified, output goes to the
  5140.              current default output channel, which starts out as
  5141.              _S_T_D_O_U_T but may be changed by the _s_e_l_e_c_t operator.
  5142.  
  5143.  
  5144.  
  5145. Sprite v1.0                                                    78
  5146.  
  5147.  
  5148.  
  5149.  
  5150.  
  5151.  
  5152. PERL                      User Commands                      PERL
  5153.  
  5154.  
  5155.  
  5156.              If the FILEHANDLE is an EXPR, then the expression is
  5157.              evaluated and the resulting string is used to look
  5158.              up the name of the FILEHANDLE at run time.  For more
  5159.              on formats, see the section on formats later on.
  5160.  
  5161.              Note that write is NOT the opposite of read.
  5162.  
  5163.      PPrreecceeddeennccee
  5164.  
  5165.      _P_e_r_l operators have the following associativity and pre-
  5166.      cedence:
  5167.  
  5168.      nonassoc  print printf exec system sort reverse
  5169.                     chmod chown kill unlink utime die return
  5170.      left      ,
  5171.      right     = += -= *= etc.
  5172.      right     ?:
  5173.      nonassoc  ..
  5174.      left      ||
  5175.      left      &&
  5176.      left      | ^
  5177.      left      &
  5178.      nonassoc  == != <=> eq ne cmp
  5179.      nonassoc  < > <= >= lt gt le ge
  5180.      nonassoc  chdir exit eval reset sleep rand umask
  5181.      nonassoc  -r -w -x etc.
  5182.      left      << >>
  5183.      left      + - .
  5184.      left      * / % x
  5185.      left      =~ !~
  5186.      right     ! ~ and unary minus
  5187.      right     **
  5188.      nonassoc  ++ --
  5189.      left      '('
  5190.  
  5191.      As mentioned earlier, if any list operator (print, etc.) or
  5192.      any unary operator (chdir, etc.) is followed by a left
  5193.      parenthesis as the next token on the same line, the operator
  5194.      and arguments within parentheses are taken to be of highest
  5195.      precedence, just like a normal function call.  Examples:
  5196.  
  5197.           chdir $foo || die;       # (chdir $foo) || die
  5198.           chdir($foo) || die;      # (chdir $foo) || die
  5199.           chdir ($foo) || die;     # (chdir $foo) || die
  5200.           chdir +($foo) || die;    # (chdir $foo) || die
  5201.  
  5202.      but, because * is higher precedence than ||:
  5203.  
  5204.           chdir $foo * 20;         # chdir ($foo * 20)
  5205.           chdir($foo) * 20;        # (chdir $foo) * 20
  5206.           chdir ($foo) * 20;       # (chdir $foo) * 20
  5207.           chdir +($foo) * 20;      # chdir ($foo * 20)
  5208.  
  5209.  
  5210.  
  5211. Sprite v1.0                                                    79
  5212.  
  5213.  
  5214.  
  5215.  
  5216.  
  5217.  
  5218. PERL                      User Commands                      PERL
  5219.  
  5220.  
  5221.  
  5222.           rand 10 * 20;            # rand (10 * 20)
  5223.           rand(10) * 20;           # (rand 10) * 20
  5224.           rand (10) * 20;          # (rand 10) * 20
  5225.           rand +(10) * 20;         # rand (10 * 20)
  5226.  
  5227.      In the absence of parentheses, the precedence of list opera-
  5228.      tors such as print, sort or chmod is either very high or
  5229.      very low depending on whether you look at the left side of
  5230.      operator or the right side of it.  For example, in
  5231.  
  5232.           @ary = (1, 3, sort 4, 2);
  5233.           print @ary;         # prints 1324
  5234.  
  5235.      the commas on the right of the sort are evaluated before the
  5236.      sort, but the commas on the left are evaluated after.  In
  5237.      other words, list operators tend to gobble up all the argu-
  5238.      ments that follow them, and then act like a simple term with
  5239.      regard to the preceding expression.  Note that you have to
  5240.      be careful with parens:
  5241.  
  5242.           # These evaluate exit before doing the print:
  5243.           print($foo, exit);  # Obviously not what you want.
  5244.           print $foo, exit;   # Nor is this.
  5245.  
  5246.           # These do the print before evaluating exit:
  5247.           (print $foo), exit; # This is what you want.
  5248.           print($foo), exit;  # Or this.
  5249.           print ($foo), exit; # Or even this.
  5250.  
  5251.      Also note that
  5252.  
  5253.           print ($foo & 255) + 1, "\n";
  5254.  
  5255.      probably doesn't do what you expect at first glance.
  5256.  
  5257.      SSuubbrroouuttiinneess
  5258.  
  5259.      A subroutine may be declared as follows:
  5260.  
  5261.          sub NAME BLOCK
  5262.  
  5263.  
  5264.      Any arguments passed to the routine come in as array @_,
  5265.      that is ($_[0], $_[1], ...).  The array @_ is a local array,
  5266.      but its values are references to the actual scalar parame-
  5267.      ters.  The return value of the subroutine is the value of
  5268.      the last expression evaluated, and can be either an array
  5269.      value or a scalar value.  Alternately, a return statement
  5270.      may be used to specify the returned value and exit the sub-
  5271.      routine.  To create local variables see the _l_o_c_a_l operator.
  5272.  
  5273.      A subroutine is called using the _d_o operator or the &
  5274.  
  5275.  
  5276.  
  5277. Sprite v1.0                                                    80
  5278.  
  5279.  
  5280.  
  5281.  
  5282.  
  5283.  
  5284. PERL                      User Commands                      PERL
  5285.  
  5286.  
  5287.  
  5288.      operator.
  5289.  
  5290.      Example:
  5291.  
  5292.           sub MAX {
  5293.                local($max) = pop(@_);
  5294.                foreach $foo (@_) {
  5295.                     $max = $foo if $max < $foo;
  5296.                }
  5297.                $max;
  5298.           }
  5299.  
  5300.           ...
  5301.           $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  5302.  
  5303.      Example:
  5304.  
  5305.           # get a line, combining continuation lines
  5306.           #  that start with whitespace
  5307.           sub get_line {
  5308.                $thisline = $lookahead;
  5309.                line: while ($lookahead = <STDIN>) {
  5310.                     if ($lookahead =~ /^[ \t]/) {
  5311.                          $thisline .= $lookahead;
  5312.                     }
  5313.                     else {
  5314.                          last line;
  5315.                     }
  5316.                }
  5317.                $thisline;
  5318.           }
  5319.  
  5320.           $lookahead = <STDIN>;    # get first line
  5321.           while ($_ = do get_line()) {
  5322.                ...
  5323.           }
  5324.  
  5325.      Use array assignment to a local list to name your formal arguments:
  5326.  
  5327.           sub maybeset {
  5328.                local($key, $value) = @_;
  5329.                $foo{$key} = $value unless $foo{$key};
  5330.           }
  5331.  
  5332.      This also has the effect of turning call-by-reference into
  5333.      call-by-value, since the assignment copies the values.
  5334.  
  5335.      Subroutines may be called recursively.  If a subroutine is
  5336.      called using the & form, the argument list is optional.  If
  5337.      omitted, no @_ array is set up for the subroutine; the @_
  5338.      array at the time of the call is visible to subroutine
  5339.      instead.
  5340.  
  5341.  
  5342.  
  5343. Sprite v1.0                                                    81
  5344.  
  5345.  
  5346.  
  5347.  
  5348.  
  5349.  
  5350. PERL                      User Commands                      PERL
  5351.  
  5352.  
  5353.  
  5354.           do foo(1,2,3);      # pass three arguments
  5355.           &foo(1,2,3);        # the same
  5356.  
  5357.           do foo();      # pass a null list
  5358.           &foo();             # the same
  5359.           &foo;               # pass no arguments--more efficient
  5360.  
  5361.  
  5362.      PPaassssiinngg BByy RReeffeerreennccee
  5363.  
  5364.      Sometimes you don't want to pass the value of an array to a
  5365.      subroutine but rather the name of it, so that the subroutine
  5366.      can modify the global copy of it rather than working with a
  5367.      local copy.  In perl you can refer to all the objects of a
  5368.      particular name by prefixing the name with a star: *foo.
  5369.      When evaluated, it produces a scalar value that represents
  5370.      all the objects of that name, including any filehandle, for-
  5371.      mat or subroutine.  When assigned to within a local() opera-
  5372.      tion, it causes the name mentioned to refer to whatever *
  5373.      value was assigned to it.  Example:
  5374.  
  5375.           sub doubleary {
  5376.               local(*someary) = @_;
  5377.               foreach $elem (@someary) {
  5378.                $elem *= 2;
  5379.               }
  5380.           }
  5381.           do doubleary(*foo);
  5382.           do doubleary(*bar);
  5383.  
  5384.      Assignment to *name is currently recommended only inside a
  5385.      local().  You can actually assign to *name anywhere, but the
  5386.      previous referent of *name may be stranded forever.  This
  5387.      may or may not bother you.
  5388.  
  5389.      Note that scalars are already passed by reference, so you
  5390.      can modify scalar arguments without using this mechanism by
  5391.      referring explicitly to the $_[nnn] in question.  You can
  5392.      modify all the elements of an array by passing all the ele-
  5393.      ments as scalars, but you have to use the * mechanism to
  5394.      push, pop or change the size of an array.  The * mechanism
  5395.      will probably be more efficient in any case.
  5396.  
  5397.      Since a *name value contains unprintable binary data, if it
  5398.      is used as an argument in a print, or as a %s argument in a
  5399.      printf or sprintf, it then has the value '*name', just so it
  5400.      prints out pretty.
  5401.  
  5402.      Even if you don't want to modify an array, this mechanism is
  5403.      useful for passing multiple arrays in a single LIST, since
  5404.      normally the LIST mechanism will merge all the array values
  5405.      so that you can't extract out the individual arrays.
  5406.  
  5407.  
  5408.  
  5409. Sprite v1.0                                                    82
  5410.  
  5411.  
  5412.  
  5413.  
  5414.  
  5415.  
  5416. PERL                      User Commands                      PERL
  5417.  
  5418.  
  5419.  
  5420.      RReegguullaarr EExxpprreessssiioonnss
  5421.  
  5422.      The patterns used in pattern matching are regular expres-
  5423.      sions such as those supplied in the Version 8 regexp rou-
  5424.      tines.  (In fact, the routines are derived from Henry
  5425.      Spencer's freely redistributable reimplementation of the V8
  5426.      routines.) In addition, \w matches an alphanumeric character
  5427.      (including "_") and \W a nonalphanumeric.  Word boundaries
  5428.      may be matched by \b, and non-boundaries by \B.  A whi-
  5429.      tespace character is matched by \s, non-whitespace by \S.  A
  5430.      numeric character is matched by \d, non-numeric by \D.  You
  5431.      may use \w, \s and \d within character classes.  Also, \n,
  5432.      \r, \f, \t and \NNN have their normal interpretations.
  5433.      Within character classes \b represents backspace rather than
  5434.      a word boundary.  Alternatives may be separated by |.  The
  5435.      bracketing construct ( ... ) may also be used, in which case
  5436.      \<digit> matches the digit'th substring.  (Outside of the
  5437.      pattern, always use $ instead of \ in front of the digit.
  5438.      The scope of $<digit> (and $`, $& and $') extends to the end
  5439.      of the enclosing BLOCK or eval string, or to the next pat-
  5440.      tern match with subexpressions.  The \<digit> notation some-
  5441.      times works outside the current pattern, but should not be
  5442.      relied upon.) You may have as many parentheses as you wish.
  5443.      If you have more than 9 substrings, the variables $10, $11,
  5444.      ... refer to the corresponding substring.  Within the pat-
  5445.      tern, \10, \11, etc. refer back to substrings if there have
  5446.      been at least that many left parens before the backrefer-
  5447.      ence.  Otherwise (for backward compatibilty) \10 is the same
  5448.      as \010, a backspace, and \11 the same as \011, a tab.  And
  5449.      so on.  (\1 through \9 are always backreferences.)
  5450.  
  5451.      $+ returns whatever the last bracket match matched.  $&
  5452.      returns the entire matched string.  ($0 used to return the
  5453.      same thing, but not any more.) $` returns everything before
  5454.      the matched string.  $' returns everything after the matched
  5455.      string.  Examples:
  5456.  
  5457.           s/^([^ ]*) *([^ ]*)/$2 $1/;   # swap first two words
  5458.  
  5459.           if (/Time: (..):(..):(..)/) {
  5460.                $hours = $1;
  5461.                $minutes = $2;
  5462.                $seconds = $3;
  5463.           }
  5464.  
  5465.      By default, the ^ character is only guaranteed to match at
  5466.      the beginning of the string, the $ character only at the end
  5467.      (or before the newline at the end) and _p_e_r_l does certain
  5468.      optimizations with the assumption that the string contains
  5469.      only one line.  The behavior of ^ and $ on embedded newlines
  5470.      will be inconsistent.  You may, however, wish to treat a
  5471.      string as a multi-line buffer, such that the ^ will match
  5472.  
  5473.  
  5474.  
  5475. Sprite v1.0                                                    83
  5476.  
  5477.  
  5478.  
  5479.  
  5480.  
  5481.  
  5482. PERL                      User Commands                      PERL
  5483.  
  5484.  
  5485.  
  5486.      after any newline within the string, and $ will match before
  5487.      any newline.  At the cost of a little more overhead, you can
  5488.      do this by setting the variable $* to 1.  Setting it back to
  5489.      0 makes _p_e_r_l revert to its old behavior.
  5490.  
  5491.      To facilitate multi-line substitutions, the . character
  5492.      never matches a newline (even when $* is 0).  In particular,
  5493.      the following leaves a newline on the $_ string:
  5494.  
  5495.           $_ = <STDIN>;
  5496.           s/.*(some_string).*/$1/;
  5497.  
  5498.      If the newline is unwanted, try one of
  5499.  
  5500.           s/.*(some_string).*\n/$1/;
  5501.           s/.*(some_string)[^\000]*/$1/;
  5502.           s/.*(some_string)(.|\n)*/$1/;
  5503.           chop; s/.*(some_string).*/$1/;
  5504.           /(some_string)/ && ($_ = $1);
  5505.  
  5506.      Any item of a regular expression may be followed with digits
  5507.      in curly brackets of the form {n,m}, where n gives the
  5508.      minimum number of times to match the item and m gives the
  5509.      maximum.  The form {n} is equivalent to {n,n} and matches
  5510.      exactly n times.  The form {n,} matches n or more times.
  5511.      (If a curly bracket occurs in any other context, it is
  5512.      treated as a regular character.) The * modifier is
  5513.      equivalent to {0,}, the + modifier to {1,} and the ? modif-
  5514.      ier to {0,1}.  There is no limit to the size of n or m, but
  5515.      large numbers will chew up more memory.
  5516.  
  5517.      You will note that all backslashed metacharacters in _p_e_r_l
  5518.      are alphanumeric, such as \b, \w, \n.  Unlike some other
  5519.      regular expression languages, there are no backslashed sym-
  5520.      bols that aren't alphanumeric.  So anything that looks like
  5521.      \\, \(, \), \<, \>, \{, or \} is always interpreted as a
  5522.      literal character, not a metacharacter.  This makes it sim-
  5523.      ple to quote a string that you want to use for a pattern but
  5524.      that you are afraid might contain metacharacters.  Simply
  5525.      quote all the non-alphanumeric characters:
  5526.  
  5527.           $pattern =~ s/(\W)/\\$1/g;
  5528.  
  5529.  
  5530.      FFoorrmmaattss
  5531.  
  5532.      Output record formats for use with the _w_r_i_t_e operator may
  5533.      declared as follows:
  5534.  
  5535.          format NAME =
  5536.          FORMLIST
  5537.          .
  5538.  
  5539.  
  5540.  
  5541. Sprite v1.0                                                    84
  5542.  
  5543.  
  5544.  
  5545.  
  5546.  
  5547.  
  5548. PERL                      User Commands                      PERL
  5549.  
  5550.  
  5551.  
  5552.      If name is omitted, format "STDOUT" is defined.  FORMLIST
  5553.      consists of a sequence of lines, each of which may be of one
  5554.      of three types:
  5555.  
  5556.      1.  A comment.
  5557.  
  5558.      2.  A "picture" line giving the format for one output line.
  5559.  
  5560.      3.  An argument line supplying values to plug into a picture
  5561.          line.
  5562.  
  5563.      Picture lines are printed exactly as they look, except for
  5564.      certain fields that substitute values into the line.  Each
  5565.      picture field starts with either @ or ^.  The @ field (not
  5566.      to be confused with the array marker @) is the normal case;
  5567.      ^ fields are used to do rudimentary multi-line text block
  5568.      filling.  The length of the field is supplied by padding out
  5569.      the field with multiple <, >, or | characters to specify,
  5570.      respectively, left justification, right justification, or
  5571.      centering.  As an alternate form of right justification, you
  5572.      may also use # characters (with an optional .) to specify a
  5573.      numeric field.  (Use of ^ instead of @ causes the field to
  5574.      be blanked if undefined.) If any of the values supplied for
  5575.      these fields contains a newline, only the text up to the
  5576.      newline is printed.  The special field @* can be used for
  5577.      printing multi-line values.  It should appear by itself on a
  5578.      line.
  5579.  
  5580.      The values are specified on the following line, in the same
  5581.      order as the picture fields.  The values should be separated
  5582.      by commas.
  5583.  
  5584.      Picture fields that begin with ^ rather than @ are treated
  5585.      specially.  The value supplied must be a scalar variable
  5586.      name which contains a text string.  _P_e_r_l puts as much text
  5587.      as it can into the field, and then chops off the front of
  5588.      the string so that the next time the variable is referenced,
  5589.      more of the text can be printed.  Normally you would use a
  5590.      sequence of fields in a vertical stack to print out a block
  5591.      of text.  If you like, you can end the final field with ...,
  5592.      which will appear in the output if the text was too long to
  5593.      appear in its entirety.  You can change which characters are
  5594.      legal to break on by changing the variable $: to a list of
  5595.      the desired characters.
  5596.  
  5597.      Since use of ^ fields can produce variable length records if
  5598.      the text to be formatted is short, you can suppress blank
  5599.      lines by putting the tilde (~) character anywhere in the
  5600.      line.  (Normally you should put it in the front if possible,
  5601.      for visibility.) The tilde will be translated to a space
  5602.      upon output.  If you put a second tilde contiguous to the
  5603.      first, the line will be repeated until all the fields on the
  5604.  
  5605.  
  5606.  
  5607. Sprite v1.0                                                    85
  5608.  
  5609.  
  5610.  
  5611.  
  5612.  
  5613.  
  5614. PERL                      User Commands                      PERL
  5615.  
  5616.  
  5617.  
  5618.      line are exhausted.  (If you use a field of the @ variety,
  5619.      the expression you supply had better not give the same value
  5620.      every time forever!)
  5621.  
  5622.      Examples:
  5623.  
  5624.      # a report on the /etc/passwd file
  5625.      format STDOUT_TOP =
  5626.                              Passwd File
  5627.      Name                Login    Office   Uid   Gid Home
  5628.      ------------------------------------------------------------------
  5629.      .
  5630.      format STDOUT =
  5631.      @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  5632.      $name,              $login,  $office,$uid,$gid, $home
  5633.      .
  5634.  
  5635.      # a report from a bug report form
  5636.      format STDOUT_TOP =
  5637.                              Bug Reports
  5638.      @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  5639.      $system,                      $%,         $date
  5640.      ------------------------------------------------------------------
  5641.      .
  5642.      format STDOUT =
  5643.      Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5644.               $subject
  5645.      Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5646.             $index,                       $description
  5647.      Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5648.                $priority,        $date,   $description
  5649.      From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5650.            $from,                         $description
  5651.      Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5652.                   $programmer,            $description
  5653.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5654.                                           $description
  5655.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5656.                                           $description
  5657.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5658.                                           $description
  5659.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  5660.                                           $description
  5661.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  5662.                                           $description
  5663.      .
  5664.  
  5665.      It is possible to intermix prints with writes on the same
  5666.      output channel, but you'll have to handle $- (lines left on
  5667.      the page) yourself.
  5668.  
  5669.      If you are printing lots of fields that are usually blank,
  5670.  
  5671.  
  5672.  
  5673. Sprite v1.0                                                    86
  5674.  
  5675.  
  5676.  
  5677.  
  5678.  
  5679.  
  5680. PERL                      User Commands                      PERL
  5681.  
  5682.  
  5683.  
  5684.      you should consider using the reset operator between
  5685.      records.  Not only is it more efficient, but it can prevent
  5686.      the bug of adding another field and forgetting to zero it.
  5687.  
  5688.      IInntteerrpprroocceessss CCoommmmuunniiccaattiioonn
  5689.  
  5690.      The IPC facilities of perl are built on the Berkeley socket
  5691.      mechanism.  If you don't have sockets, you can ignore this
  5692.      section.  The calls have the same names as the corresponding
  5693.      system calls, but the arguments tend to differ, for two rea-
  5694.      sons.  First, perl file handles work differently than C file
  5695.      descriptors.  Second, perl already knows the length of its
  5696.      strings, so you don't need to pass that information.  Here
  5697.      is a sample client (untested):
  5698.  
  5699.           ($them,$port) = @ARGV;
  5700.           $port = 2345 unless $port;
  5701.           $them = 'localhost' unless $them;
  5702.  
  5703.           $SIG{'INT'} = 'dokill';
  5704.           sub dokill { kill 9,$child if $child; }
  5705.  
  5706.           require 'sys/socket.ph';
  5707.  
  5708.           $sockaddr = 'S n a4 x8';
  5709.           chop($hostname = `hostname`);
  5710.  
  5711.           ($name, $aliases, $proto) = getprotobyname('tcp');
  5712.           ($name, $aliases, $port) = getservbyname($port, 'tcp')
  5713.                unless $port =~ /^\d+$/;
  5714.           ($name, $aliases, $type, $len, $thisaddr) =
  5715.                               gethostbyname($hostname);
  5716.           ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
  5717.  
  5718.           $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
  5719.           $that = pack($sockaddr, &AF_INET, $port, $thataddr);
  5720.  
  5721.           socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  5722.           bind(S, $this) || die "bind: $!";
  5723.           connect(S, $that) || die "connect: $!";
  5724.  
  5725.           select(S); $| = 1; select(stdout);
  5726.  
  5727.           if ($child = fork) {
  5728.                while (<>) {
  5729.                     print S;
  5730.                }
  5731.                sleep 3;
  5732.                do dokill();
  5733.           }
  5734.           else {
  5735.                while (<S>) {
  5736.  
  5737.  
  5738.  
  5739. Sprite v1.0                                                    87
  5740.  
  5741.  
  5742.  
  5743.  
  5744.  
  5745.  
  5746. PERL                      User Commands                      PERL
  5747.  
  5748.  
  5749.  
  5750.                     print;
  5751.                }
  5752.           }
  5753.  
  5754.      And here's a server:
  5755.  
  5756.           ($port) = @ARGV;
  5757.           $port = 2345 unless $port;
  5758.  
  5759.           require 'sys/socket.ph';
  5760.  
  5761.           $sockaddr = 'S n a4 x8';
  5762.  
  5763.           ($name, $aliases, $proto) = getprotobyname('tcp');
  5764.           ($name, $aliases, $port) = getservbyname($port, 'tcp')
  5765.                unless $port =~ /^\d+$/;
  5766.  
  5767.           $this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");
  5768.  
  5769.           select(NS); $| = 1; select(stdout);
  5770.  
  5771.           socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  5772.           bind(S, $this) || die "bind: $!";
  5773.           listen(S, 5) || die "connect: $!";
  5774.  
  5775.           select(S); $| = 1; select(stdout);
  5776.  
  5777.           for (;;) {
  5778.                print "Listening again\n";
  5779.                ($addr = accept(NS,S)) || die $!;
  5780.                print "accept ok\n";
  5781.  
  5782.                ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
  5783.                @inetaddr = unpack('C4',$inetaddr);
  5784.                print "$af $port @inetaddr\n";
  5785.  
  5786.                while (<NS>) {
  5787.                     print;
  5788.                     print NS;
  5789.                }
  5790.           }
  5791.  
  5792.  
  5793.      PPrreeddeeffiinneedd NNaammeess
  5794.  
  5795.      The following names have special meaning to _p_e_r_l.  I could
  5796.      have used alphabetic symbols for some of these, but I didn't
  5797.      want to take the chance that someone would say reset
  5798.      "a-zA-Z" and wipe them all out.  You'll just have to suffer
  5799.      along with these silly symbols.  Most of them have reason-
  5800.      able mnemonics, or analogues in one of the shells.
  5801.  
  5802.  
  5803.  
  5804.  
  5805. Sprite v1.0                                                    88
  5806.  
  5807.  
  5808.  
  5809.  
  5810.  
  5811.  
  5812. PERL                      User Commands                      PERL
  5813.  
  5814.  
  5815.  
  5816.      $_      The default input and pattern-searching space.  The
  5817.              following pairs are equivalent:
  5818.  
  5819.                   while (<>) {...     # only equivalent in while!
  5820.                   while ($_ = <>) {...
  5821.  
  5822.                   /^Subject:/
  5823.                   $_ =~ /^Subject:/
  5824.  
  5825.                   y/a-z/A-Z/
  5826.                   $_ =~ y/a-z/A-Z/
  5827.  
  5828.                   chop
  5829.                   chop($_)
  5830.  
  5831.              (Mnemonic: underline is understood in certain opera-
  5832.              tions.)
  5833.  
  5834.      $.      The current input line number of the last filehandle
  5835.              that was read.  Readonly.  Remember that only an
  5836.              explicit close on the filehandle resets the line
  5837.              number.  Since <> never does an explicit close, line
  5838.              numbers increase across ARGV files (but see examples
  5839.              under eof).  (Mnemonic: many programs use . to mean
  5840.              the current line number.)
  5841.  
  5842.      $/      The input record separator, newline by default.
  5843.              Works like _a_w_k's RS variable, including treating
  5844.              blank lines as delimiters if set to the null string.
  5845.              You may set it to a multicharacter string to match a
  5846.              multi-character delimiter.  (Mnemonic: / is used to
  5847.              delimit line boundaries when quoting poetry.)
  5848.  
  5849.      $,      The output field separator for the print operator.
  5850.              Ordinarily the print operator simply prints out the
  5851.              comma separated fields you specify.  In order to get
  5852.              behavior more like _a_w_k, set this variable as you
  5853.              would set _a_w_k's OFS variable to specify what is
  5854.              printed between fields.  (Mnemonic: what is printed
  5855.              when there is a , in your print statement.)
  5856.  
  5857.      $"      This is like $, except that it applies to array
  5858.              values interpolated into a double-quoted string (or
  5859.              similar interpreted string).  Default is a space.
  5860.              (Mnemonic: obvious, I think.)
  5861.  
  5862.      $\      The output record separator for the print operator.
  5863.              Ordinarily the print operator simply prints out the
  5864.              comma separated fields you specify, with no trailing
  5865.              newline or record separator assumed.  In order to
  5866.              get behavior more like _a_w_k, set this variable as you
  5867.              would set _a_w_k's ORS variable to specify what is
  5868.  
  5869.  
  5870.  
  5871. Sprite v1.0                                                    89
  5872.  
  5873.  
  5874.  
  5875.  
  5876.  
  5877.  
  5878. PERL                      User Commands                      PERL
  5879.  
  5880.  
  5881.  
  5882.              printed at the end of the print.  (Mnemonic: you set
  5883.              $\ instead of adding \n at the end of the print.
  5884.              Also, it's just like /, but it's what you get "back"
  5885.              from _p_e_r_l.)
  5886.  
  5887.      $#      The output format for printed numbers.  This vari-
  5888.              able is a half-hearted attempt to emulate _a_w_k's OFMT
  5889.              variable.  There are times, however, when _a_w_k and
  5890.              _p_e_r_l have differing notions of what is in fact
  5891.              numeric.  Also, the initial value is %.20g rather
  5892.              than %.6g, so you need to set $# explicitly to get
  5893.              _a_w_k's value.  (Mnemonic: # is the number sign.)
  5894.  
  5895.      $%      The current page number of the currently selected
  5896.              output channel.  (Mnemonic: % is page number in
  5897.              nroff.)
  5898.  
  5899.      $=      The current page length (printable lines) of the
  5900.              currently selected output channel.  Default is 60.
  5901.              (Mnemonic: = has horizontal lines.)
  5902.  
  5903.      $-      The number of lines left on the page of the
  5904.              currently selected output channel.  (Mnemonic:
  5905.              lines_on_page - lines_printed.)
  5906.  
  5907.      $~      The name of the current report format for the
  5908.              currently selected output channel.  Default is name
  5909.              of the filehandle.  (Mnemonic: brother to $^.)
  5910.  
  5911.      $^      The name of the current top-of-page format for the
  5912.              currently selected output channel.  Default is name
  5913.              of the filehandle with "_TOP" appended.  (Mnemonic:
  5914.              points to top of page.)
  5915.  
  5916.      $|      If set to nonzero, forces a flush after every write
  5917.              or print on the currently selected output channel.
  5918.              Default is 0.  Note that _S_T_D_O_U_T will typically be
  5919.              line buffered if output is to the terminal and block
  5920.              buffered otherwise.  Setting this variable is useful
  5921.              primarily when you are outputting to a pipe, such as
  5922.              when you are running a _p_e_r_l script under rsh and
  5923.              want to see the output as it's happening.
  5924.              (Mnemonic: when you want your pipes to be piping
  5925.              hot.)
  5926.  
  5927.      $$      The process number of the _p_e_r_l running this script.
  5928.              (Mnemonic: same as shells.)
  5929.  
  5930.      $?      The status returned by the last pipe close, backtick
  5931.              (``) command or _s_y_s_t_e_m operator.  Note that this is
  5932.              the status word returned by the wait() system call,
  5933.              so the exit value of the subprocess is actually ($?
  5934.  
  5935.  
  5936.  
  5937. Sprite v1.0                                                    90
  5938.  
  5939.  
  5940.  
  5941.  
  5942.  
  5943.  
  5944. PERL                      User Commands                      PERL
  5945.  
  5946.  
  5947.  
  5948.              >> 8).  $? & 255 gives which signal, if any, the
  5949.              process died from, and whether there was a core
  5950.              dump.  (Mnemonic: similar to sh and ksh.)
  5951.  
  5952.      $&      The string matched by the last pattern match (not
  5953.              counting any matches hidden within a BLOCK or eval
  5954.              enclosed by the current BLOCK).  (Mnemonic: like &
  5955.              in some editors.)
  5956.  
  5957.      $`      The string preceding whatever was matched by the
  5958.              last pattern match (not counting any matches hidden
  5959.              within a BLOCK or eval enclosed by the current
  5960.              BLOCK).  (Mnemonic: ` often precedes a quoted
  5961.              string.)
  5962.  
  5963.      $'      The string following whatever was matched by the
  5964.              last pattern match (not counting any matches hidden
  5965.              within a BLOCK or eval enclosed by the current
  5966.              BLOCK).  (Mnemonic: ' often follows a quoted
  5967.              string.) Example:
  5968.  
  5969.                   $_ = 'abcdefghi';
  5970.                   /def/;
  5971.                   print "$`:$&:$'\n";      # prints abc:def:ghi
  5972.  
  5973.  
  5974.      $+      The last bracket matched by the last search pattern.
  5975.              This is useful if you don't know which of a set of
  5976.              alternative patterns matched.  For example:
  5977.  
  5978.                  /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  5979.  
  5980.              (Mnemonic: be positive and forward looking.)
  5981.  
  5982.      $*      Set to 1 to do multiline matching within a string, 0
  5983.              to tell _p_e_r_l that it can assume that strings contain
  5984.              a single line, for the purpose of optimizing pattern
  5985.              matches.  Pattern matches on strings containing mul-
  5986.              tiple newlines can produce confusing results when $*
  5987.              is 0.  Default is 0.  (Mnemonic: * matches multiple
  5988.              things.) Note that this variable only influences the
  5989.              interpretation of ^ and $.  A literal newline can be
  5990.              searched for even when $* == 0.
  5991.  
  5992.      $0      Contains the name of the file containing the _p_e_r_l
  5993.              script being executed.  Assigning to $0 modifies the
  5994.              argument area that the ps(1) program sees.
  5995.              (Mnemonic: same as sh and ksh.)
  5996.  
  5997.      $<digit>
  5998.              Contains the subpattern from the corresponding set
  5999.              of parentheses in the last pattern matched, not
  6000.  
  6001.  
  6002.  
  6003. Sprite v1.0                                                    91
  6004.  
  6005.  
  6006.  
  6007.  
  6008.  
  6009.  
  6010. PERL                      User Commands                      PERL
  6011.  
  6012.  
  6013.  
  6014.              counting patterns matched in nested blocks that have
  6015.              been exited already.  (Mnemonic: like \digit.)
  6016.  
  6017.      $[      The index of the first element in an array, and of
  6018.              the first character in a substring.  Default is 0,
  6019.              but you could set it to 1 to make _p_e_r_l behave more
  6020.              like _a_w_k (or Fortran) when subscripting and when
  6021.              evaluating the index() and substr() functions.
  6022.              (Mnemonic: [ begins subscripts.)
  6023.  
  6024.      $]      The string printed out when you say "perl -v".  It
  6025.              can be used to determine at the beginning of a
  6026.              script whether the perl interpreter executing the
  6027.              script is in the right range of versions.  If used
  6028.              in a numeric context, returns the version +
  6029.              patchlevel / 1000.  Example:
  6030.  
  6031.                   # see if getc is available
  6032.                      ($version,$patchlevel) =
  6033.                         $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
  6034.                      print STDERR "(No filename completion available.)\n"
  6035.                         if $version * 1000 + $patchlevel < 2016;
  6036.  
  6037.              or, used numerically,
  6038.  
  6039.                   warn "No checksumming!\n" if $] < 3.019;
  6040.  
  6041.              (Mnemonic: Is this version of perl in the right
  6042.              bracket?)
  6043.  
  6044.      $;      The subscript separator for multi-dimensional array
  6045.              emulation.  If you refer to an associative array
  6046.              element as
  6047.                   $foo{$a,$b,$c}
  6048.  
  6049.              it really means
  6050.  
  6051.                   $foo{join($;, $a, $b, $c)}
  6052.  
  6053.              But don't put
  6054.  
  6055.                   @foo{$a,$b,$c}      # a slice--note the @
  6056.  
  6057.              which means
  6058.  
  6059.                   ($foo{$a},$foo{$b},$foo{$c})
  6060.  
  6061.              Default is "\034", the same as SUBSEP in _a_w_k.  Note
  6062.              that if your keys contain binary data there might
  6063.              not be any safe value for $;.  (Mnemonic: comma (the
  6064.              syntactic subscript separator) is a semi-semicolon.
  6065.              Yeah, I know, it's pretty lame, but $, is already
  6066.  
  6067.  
  6068.  
  6069. Sprite v1.0                                                    92
  6070.  
  6071.  
  6072.  
  6073.  
  6074.  
  6075.  
  6076. PERL                      User Commands                      PERL
  6077.  
  6078.  
  6079.  
  6080.              taken for something more important.)
  6081.  
  6082.      $!      If used in a numeric context, yields the current
  6083.              value of errno, with all the usual caveats.  (This
  6084.              means that you shouldn't depend on the value of $!
  6085.              to be anything in particular unless you've gotten a
  6086.              specific error return indicating a system error.) If
  6087.              used in a string context, yields the corresponding
  6088.              system error string.  You can assign to $! in order
  6089.              to set errno if, for instance, you want $! to return
  6090.              the string for error n, or you want to set the exit
  6091.              value for the die operator.  (Mnemonic: What just
  6092.              went bang?)
  6093.  
  6094.      $@      The perl syntax error message from the last eval
  6095.              command.  If null, the last eval parsed and executed
  6096.              correctly (although the operations you invoked may
  6097.              have failed in the normal fashion).  (Mnemonic:
  6098.              Where was the syntax error "at"?)
  6099.  
  6100.      $<      The real uid of this process.  (Mnemonic: it's the
  6101.              uid you came FROM, if you're running setuid.)
  6102.  
  6103.      $>      The effective uid of this process.  Example:
  6104.  
  6105.                   $< = $>;  # set real uid to the effective uid
  6106.                   ($<,$>) = ($>,$<);  # swap real and effective uid
  6107.  
  6108.              (Mnemonic: it's the uid you went TO, if you're run-
  6109.              ning setuid.) Note: $< and $> can only be swapped on
  6110.              machines supporting setreuid().
  6111.  
  6112.      $(      The real gid of this process.  If you are on a
  6113.              machine that supports membership in multiple groups
  6114.              simultaneously, gives a space separated list of
  6115.              groups you are in.  The first number is the one
  6116.              returned by getgid(), and the subsequent ones by
  6117.              getgroups(), one of which may be the same as the
  6118.              first number.  (Mnemonic: parentheses are used to
  6119.              GROUP things.  The real gid is the group you LEFT,
  6120.              if you're running setgid.)
  6121.  
  6122.      $)      The effective gid of this process.  If you are on a
  6123.              machine that supports membership in multiple groups
  6124.              simultaneously, gives a space separated list of
  6125.              groups you are in.  The first number is the one
  6126.              returned by getegid(), and the subsequent ones by
  6127.              getgroups(), one of which may be the same as the
  6128.              first number.  (Mnemonic: parentheses are used to
  6129.              GROUP things.  The effective gid is the group that's
  6130.              RIGHT for you, if you're running setgid.)
  6131.  
  6132.  
  6133.  
  6134.  
  6135. Sprite v1.0                                                    93
  6136.  
  6137.  
  6138.  
  6139.  
  6140.  
  6141.  
  6142. PERL                      User Commands                      PERL
  6143.  
  6144.  
  6145.  
  6146.              Note: $<, $>, $( and $) can only be set on machines
  6147.              that support the corresponding set[re][ug]id() rou-
  6148.              tine.  $( and $) can only be swapped on machines
  6149.              supporting setregid().
  6150.  
  6151.      $:      The current set of characters after which a string
  6152.              may be broken to fill continuation fields (starting
  6153.              with ^) in a format.  Default is " \n-", to break on
  6154.              whitespace or hyphens.  (Mnemonic: a "colon" in poe-
  6155.              try is a part of a line.)
  6156.  
  6157.      $^D     The current value of the debugging flags.
  6158.              (Mnemonic: value of --DD switch.)
  6159.  
  6160.      $^F     The maximum system file descriptor, ordinarily 2.
  6161.              System file descriptors are passed to subprocesses,
  6162.              while higher file descriptors are not.  During an
  6163.              open, system file descriptors are preserved even if
  6164.              the open fails.  Ordinary file descriptors are
  6165.              closed before the open is attempted.
  6166.  
  6167.      $^I     The current value of the inplace-edit extension.
  6168.              Use undef to disable inplace editing.  (Mnemonic:
  6169.              value of --ii switch.)
  6170.  
  6171.      $^P     The internal flag that the debugger clears so that
  6172.              it doesn't debug itself.  You could conceivable dis-
  6173.              able debugging yourself by clearing it.
  6174.  
  6175.      $^T     The time at which the script began running, in
  6176.              seconds since the epoch.  The values returned by the
  6177.              --MM ,, --AA and --CC filetests are based on this value.
  6178.  
  6179.      $^W     The current value of the warning switch.  (Mnemonic:
  6180.              related to the --ww switch.)
  6181.  
  6182.      $^X     The name that Perl itself was executed as, from
  6183.              argv[0].
  6184.  
  6185.      $ARGV   contains the name of the current file when reading
  6186.              from <>.
  6187.  
  6188.      @ARGV   The array ARGV contains the command line arguments
  6189.              intended for the script.  Note that $#ARGV is the
  6190.              generally number of arguments minus one, since
  6191.              $ARGV[0] is the first argument, NOT the command
  6192.              name.  See $0 for the command name.
  6193.  
  6194.      @INC    The array INC contains the list of places to look
  6195.              for _p_e_r_l scripts to be evaluated by the "do EXPR"
  6196.              command or the "require" command.  It initially con-
  6197.              sists of the arguments to any --II command line
  6198.  
  6199.  
  6200.  
  6201. Sprite v1.0                                                    94
  6202.  
  6203.  
  6204.  
  6205.  
  6206.  
  6207.  
  6208. PERL                      User Commands                      PERL
  6209.  
  6210.  
  6211.  
  6212.              switches, followed by the default _p_e_r_l library,
  6213.              probably "/usr/local/lib/perl", followed by ".", to
  6214.              represent the current directory.
  6215.  
  6216.      %INC    The associative array INC contains entries for each
  6217.              filename that has been included via "do" or
  6218.              "require".  The key is the filename you specified,
  6219.              and the value is the location of the file actually
  6220.              found.  The "require" command uses this array to
  6221.              determine whether a given file has already been
  6222.              included.
  6223.  
  6224.      $ENV{expr}
  6225.              The associative array ENV contains your current
  6226.              environment.  Setting a value in ENV changes the
  6227.              environment for child processes.
  6228.  
  6229.      $SIG{expr}
  6230.              The associative array SIG is used to set signal
  6231.              handlers for various signals.  Example:
  6232.  
  6233.                   sub handler {  # 1st argument is signal name
  6234.                        local($sig) = @_;
  6235.                        print "Caught a SIG$sig--shutting down\n";
  6236.                        close(LOG);
  6237.                        exit(0);
  6238.                   }
  6239.  
  6240.                   $SIG{'INT'} = 'handler';
  6241.                   $SIG{'QUIT'} = 'handler';
  6242.                   ...
  6243.                   $SIG{'INT'} = 'DEFAULT'; # restore default action
  6244.                   $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
  6245.  
  6246.              The SIG array only contains values for the signals
  6247.              actually set within the perl script.
  6248.  
  6249.      PPaacckkaaggeess
  6250.  
  6251.      Perl provides a mechanism for alternate namespaces to pro-
  6252.      tect packages from stomping on each others variables.  By
  6253.      default, a perl script starts compiling into the package
  6254.      known as "main".  By use of the _p_a_c_k_a_g_e declaration, you can
  6255.      switch namespaces.  The scope of the package declaration is
  6256.      from the declaration itself to the end of the enclosing
  6257.      block (the same scope as the local() operator).  Typically
  6258.      it would be the first declaration in a file to be included
  6259.      by the "require" operator.  You can switch into a package in
  6260.      more than one place; it merely influences which symbol table
  6261.      is used by the compiler for the rest of that block.  You can
  6262.      refer to variables and filehandles in other packages by pre-
  6263.      fixing the identifier with the package name and a single
  6264.  
  6265.  
  6266.  
  6267. Sprite v1.0                                                    95
  6268.  
  6269.  
  6270.  
  6271.  
  6272.  
  6273.  
  6274. PERL                      User Commands                      PERL
  6275.  
  6276.  
  6277.  
  6278.      quote.  If the package name is null, the "main" package as
  6279.      assumed.
  6280.  
  6281.      Only identifiers starting with letters are stored in the
  6282.      packages symbol table.  All other symbols are kept in pack-
  6283.      age "main".  In addition, the identifiers STDIN, STDOUT,
  6284.      STDERR, ARGV, ARGVOUT, ENV, INC and SIG are forced to be in
  6285.      package "main", even when used for other purposes than their
  6286.      built-in one.  Note also that, if you have a package called
  6287.      "m", "s" or "y", the you can't use the qualified form of an
  6288.      identifier since it will be interpreted instead as a pattern
  6289.      match, a substitution or a translation.
  6290.  
  6291.      Eval'ed strings are compiled in the package in which the
  6292.      eval was compiled in.  (Assignments to $SIG{}, however,
  6293.      assume the signal handler specified is in the main package.
  6294.      Qualify the signal handler name if you wish to have a signal
  6295.      handler in a package.) For an example, examine perldb.pl in
  6296.      the perl library.  It initially switches to the DB package
  6297.      so that the debugger doesn't interfere with variables in the
  6298.      script you are trying to debug.  At various points, however,
  6299.      it temporarily switches back to the main package to evaluate
  6300.      various expressions in the context of the main package.
  6301.  
  6302.      The symbol table for a package happens to be stored in the
  6303.      associative array of that name prepended with an underscore.
  6304.      The value in each entry of the associative array is what you
  6305.      are referring to when you use the *name notation.  In fact,
  6306.      the following have the same effect (in package main, any-
  6307.      way), though the first is more efficient because it does the
  6308.      symbol table lookups at compile time:
  6309.  
  6310.           local(*foo) = *bar;
  6311.           local($_main{'foo'}) = $_main{'bar'};
  6312.  
  6313.      You can use this to print out all the variables in a pack-
  6314.      age, for instance.  Here is dumpvar.pl from the perl
  6315.      library:
  6316.           package dumpvar;
  6317.  
  6318.           sub main'dumpvar {
  6319.               ($package) = @_;
  6320.               local(*stab) = eval("*_$package");
  6321.               while (($key,$val) = each(%stab)) {
  6322.                   {
  6323.                       local(*entry) = $val;
  6324.                       if (defined $entry) {
  6325.                           print "\$$key = '$entry'\n";
  6326.                       }
  6327.  
  6328.  
  6329.  
  6330.  
  6331.  
  6332.  
  6333. Sprite v1.0                                                    96
  6334.  
  6335.  
  6336.  
  6337.  
  6338.  
  6339.  
  6340. PERL                      User Commands                      PERL
  6341.  
  6342.  
  6343.  
  6344.                       if (defined @entry) {
  6345.                           print "\@$key = (\n";
  6346.                           foreach $num ($[ .. $#entry) {
  6347.                               print "  $num\t'",$entry[$num],"'\n";
  6348.                           }
  6349.                           print ")\n";
  6350.                       }
  6351.                       if ($key ne "_$package" && defined %entry) {
  6352.                           print "\%$key = (\n";
  6353.                           foreach $key (sort keys(%entry)) {
  6354.                               print "  $key\t'",$entry{$key},"'\n";
  6355.                           }
  6356.                           print ")\n";
  6357.                       }
  6358.                   }
  6359.               }
  6360.           }
  6361.  
  6362.      Note that, even though the subroutine is compiled in package
  6363.      dumpvar, the name of the subroutine is qualified so that its
  6364.      name is inserted into package "main".
  6365.  
  6366.      SSttyyllee
  6367.  
  6368.      Each programmer will, of course, have his or her own prefer-
  6369.      ences in regards to formatting, but there are some general
  6370.      guidelines that will make your programs easier to read.
  6371.  
  6372.      1.  Just because you CAN do something a particular way
  6373.          doesn't mean that you SHOULD do it that way.  _P_e_r_l is
  6374.          designed to give you several ways to do anything, so
  6375.          consider picking the most readable one.  For instance
  6376.  
  6377.               open(FOO,$foo) || die "Can't open $foo: $!";
  6378.  
  6379.          is better than
  6380.  
  6381.               die "Can't open $foo: $!" unless open(FOO,$foo);
  6382.  
  6383.          because the second way hides the main point of the
  6384.          statement in a modifier.  On the other hand
  6385.  
  6386.               print "Starting analysis\n" if $verbose;
  6387.  
  6388.          is better than
  6389.  
  6390.               $verbose && print "Starting analysis\n";
  6391.  
  6392.          since the main point isn't whether the user typed -v or
  6393.          not.
  6394.  
  6395.          Similarly, just because an operator lets you assume
  6396.  
  6397.  
  6398.  
  6399. Sprite v1.0                                                    97
  6400.  
  6401.  
  6402.  
  6403.  
  6404.  
  6405.  
  6406. PERL                      User Commands                      PERL
  6407.  
  6408.  
  6409.  
  6410.          default arguments doesn't mean that you have to make use
  6411.          of the defaults.  The defaults are there for lazy sys-
  6412.          tems programmers writing one-shot programs.  If you want
  6413.          your program to be readable, consider supplying the
  6414.          argument.
  6415.  
  6416.          Along the same lines, just because you _c_a_n omit
  6417.          parentheses in many places doesn't mean that you ought
  6418.          to:
  6419.  
  6420.               return print reverse sort num values array;
  6421.               return print(reverse(sort num (values(%array))));
  6422.  
  6423.          When in doubt, parenthesize.  At the very least it will
  6424.          let some poor schmuck bounce on the % key in vi.
  6425.  
  6426.          Even if you aren't in doubt, consider the mental welfare
  6427.          of the person who has to maintain the code after you,
  6428.          and who will probably put parens in the wrong place.
  6429.  
  6430.      2.  Don't go through silly contortions to exit a loop at the
  6431.          top or the bottom, when _p_e_r_l provides the "last" opera-
  6432.          tor so you can exit in the middle.  Just outdent it a
  6433.          little to make it more visible:
  6434.  
  6435.              line:
  6436.               for (;;) {
  6437.                   statements;
  6438.               last line if $foo;
  6439.                   next line if /^#/;
  6440.                   statements;
  6441.               }
  6442.  
  6443.  
  6444.      3.  Don't be afraid to use loop labels--they're there to
  6445.          enhance readability as well as to allow multi-level loop
  6446.          breaks.  See last example.
  6447.  
  6448.      4.  For portability, when using features that may not be
  6449.          implemented on every machine, test the construct in an
  6450.          eval to see if it fails.  If you know what version or
  6451.          patchlevel a particular feature was implemented, you can
  6452.          test $] to see if it will be there.
  6453.  
  6454.      5.  Choose mnemonic identifiers.
  6455.  
  6456.      6.  Be consistent.
  6457.  
  6458.      DDeebbuuggggiinngg
  6459.  
  6460.      If you invoke _p_e_r_l with a --dd switch, your script will be run
  6461.      under a debugging monitor.  It will halt before the first
  6462.  
  6463.  
  6464.  
  6465. Sprite v1.0                                                    98
  6466.  
  6467.  
  6468.  
  6469.  
  6470.  
  6471.  
  6472. PERL                      User Commands                      PERL
  6473.  
  6474.  
  6475.  
  6476.      executable statement and ask you for a command, such as:
  6477.  
  6478.      h           Prints out a help message.
  6479.  
  6480.      T           Stack trace.
  6481.  
  6482.      s           Single step.  Executes until it reaches the
  6483.                  beginning of another statement.
  6484.  
  6485.      n           Next.  Executes over subroutine calls, until it
  6486.                  reaches the beginning of the next statement.
  6487.  
  6488.      f           Finish.  Executes statements until it has fin-
  6489.                  ished the current subroutine.
  6490.  
  6491.      c           Continue.  Executes until the next breakpoint is
  6492.                  reached.
  6493.  
  6494.      c line      Continue to the specified line.  Inserts a one-
  6495.                  time-only breakpoint at the specified line.
  6496.  
  6497.      <CR>        Repeat last n or s.
  6498.  
  6499.      l min+incr  List incr+1 lines starting at min.  If min is
  6500.                  omitted, starts where last listing left off.  If
  6501.                  incr is omitted, previous value of incr is used.
  6502.  
  6503.      l min-max   List lines in the indicated range.
  6504.  
  6505.      l line      List just the indicated line.
  6506.  
  6507.      l           List next window.
  6508.  
  6509.      -           List previous window.
  6510.  
  6511.      w line      List window around line.
  6512.  
  6513.      l subname   List subroutine.  If it's a long subroutine it
  6514.                  just lists the beginning.  Use "l" to list more.
  6515.  
  6516.      /pattern/   Regular expression search forward for pattern;
  6517.                  the final / is optional.
  6518.  
  6519.      ?pattern?   Regular expression search backward for pattern;
  6520.                  the final ? is optional.
  6521.  
  6522.      L           List lines that have breakpoints or actions.
  6523.  
  6524.      S           Lists the names of all subroutines.
  6525.  
  6526.  
  6527.  
  6528.  
  6529.  
  6530.  
  6531. Sprite v1.0                                                    99
  6532.  
  6533.  
  6534.  
  6535.  
  6536.  
  6537.  
  6538. PERL                      User Commands                      PERL
  6539.  
  6540.  
  6541.  
  6542.      t           Toggle trace mode on or off.
  6543.  
  6544.      b line condition
  6545.                  Set a breakpoint.  If line is omitted, sets a
  6546.                  breakpoint on the line that is about to be exe-
  6547.                  cuted.  If a condition is specified, it is
  6548.                  evaluated each time the statement is reached and
  6549.                  a breakpoint is taken only if the condition is
  6550.                  true.  Breakpoints may only be set on lines that
  6551.                  begin an executable statement.
  6552.  
  6553.      b subname condition
  6554.                  Set breakpoint at first executable line of sub-
  6555.                  routine.
  6556.  
  6557.      d line      Delete breakpoint.  If line is omitted, deletes
  6558.                  the breakpoint on the line that is about to be
  6559.                  executed.
  6560.  
  6561.      D           Delete all breakpoints.
  6562.  
  6563.      a line command
  6564.                  Set an action for line.  A multi-line command
  6565.                  may be entered by backslashing the newlines.
  6566.  
  6567.      A           Delete all line actions.
  6568.  
  6569.      < command   Set an action to happen before every debugger
  6570.                  prompt.  A multi-line command may be entered by
  6571.                  backslashing the newlines.
  6572.  
  6573.      > command   Set an action to happen after the prompt when
  6574.                  you've just given a command to return to execut-
  6575.                  ing the script.  A multi-line command may be
  6576.                  entered by backslashing the newlines.
  6577.  
  6578.      V package   List all variables in package.  Default is main
  6579.                  package.
  6580.  
  6581.      ! number    Redo a debugging command.  If number is omitted,
  6582.                  redoes the previous command.
  6583.  
  6584.      ! -number   Redo the command that was that many commands
  6585.                  ago.
  6586.  
  6587.      H -number   Display last n commands.  Only commands longer
  6588.                  than one character are listed.  If number is
  6589.                  omitted, lists them all.
  6590.  
  6591.      q or ^D     Quit.
  6592.  
  6593.  
  6594.  
  6595.  
  6596.  
  6597. Sprite v1.0                                                   100
  6598.  
  6599.  
  6600.  
  6601.  
  6602.  
  6603.  
  6604. PERL                      User Commands                      PERL
  6605.  
  6606.  
  6607.  
  6608.      command     Execute command as a perl statement.  A missing
  6609.                  semicolon will be supplied.
  6610.  
  6611.      p expr      Same as "print DB'OUT expr".  The DB'OUT
  6612.                  filehandle is opened to /dev/tty, regardless of
  6613.                  where STDOUT may be redirected to.
  6614.  
  6615.      If you want to modify the debugger, copy perldb.pl from the
  6616.      perl library to your current directory and modify it as
  6617.      necessary.  (You'll also have to put -I. on your command
  6618.      line.) You can do some customization by setting up a .perldb
  6619.      file which contains initialization code.  For instance, you
  6620.      could make aliases like these:
  6621.  
  6622.          $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
  6623.          $DB'alias{'stop'} = 's/^stop (at|in)/b/';
  6624.          $DB'alias{'.'} =
  6625.            's/^\./p "\$DB\'sub(\$DB\'line):\t",\$DB\'line[\$DB\'line]/';
  6626.  
  6627.  
  6628.      SSeettuuiidd SSccrriippttss
  6629.  
  6630.      _P_e_r_l is designed to make it easy to write secure setuid and
  6631.      setgid scripts.  Unlike shells, which are based on multiple
  6632.      substitution passes on each line of the script, _p_e_r_l uses a
  6633.      more conventional evaluation scheme with fewer hidden
  6634.      "gotchas".  Additionally, since the language has more
  6635.      built-in functionality, it has to rely less upon external
  6636.      (and possibly untrustworthy) programs to accomplish its pur-
  6637.      poses.
  6638.  
  6639.      In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are
  6640.      intrinsically insecure, but this kernel feature can be dis-
  6641.      abled.  If it is, _p_e_r_l can emulate the setuid and setgid
  6642.      mechanism when it notices the otherwise useless setuid/gid
  6643.      bits on perl scripts.  If the kernel feature isn't disabled,
  6644.      _p_e_r_l will complain loudly that your setuid script is
  6645.      insecure.  You'll need to either disable the kernel setuid
  6646.      script feature, or put a C wrapper around the script.
  6647.  
  6648.      When perl is executing a setuid script, it takes special
  6649.      precautions to prevent you from falling into any obvious
  6650.      traps.  (In some ways, a perl script is more secure than the
  6651.      corresponding C program.) Any command line argument,
  6652.      environment variable, or input is marked as "tainted", and
  6653.      may not be used, directly or indirectly, in any command that
  6654.      invokes a subshell, or in any command that modifies files,
  6655.      directories or processes.  Any variable that is set within
  6656.      an expression that has previously referenced a tainted value
  6657.      also becomes tainted (even if it is logically impossible for
  6658.      the tainted value to influence the variable).  For example:
  6659.  
  6660.  
  6661.  
  6662.  
  6663. Sprite v1.0                                                   101
  6664.  
  6665.  
  6666.  
  6667.  
  6668.  
  6669.  
  6670. PERL                      User Commands                      PERL
  6671.  
  6672.  
  6673.  
  6674.           $foo = shift;            # $foo is tainted
  6675.           $bar = $foo,'bar';       # $bar is also tainted
  6676.           $xxx = <>;               # Tainted
  6677.           $path = $ENV{'PATH'};    # Tainted, but see below
  6678.           $abc = 'abc';            # Not tainted
  6679.  
  6680.           system "echo $foo";      # Insecure
  6681.           system "/bin/echo", $foo;     # Secure (doesn't use sh)
  6682.           system "echo $bar";      # Insecure
  6683.           system "echo $abc";      # Insecure until PATH set
  6684.  
  6685.           $ENV{'PATH'} = '/bin:/usr/bin';
  6686.           $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  6687.  
  6688.           $path = $ENV{'PATH'};    # Not tainted
  6689.           system "echo $abc";      # Is secure now!
  6690.  
  6691.           open(FOO,"$foo");        # OK
  6692.           open(FOO,">$foo");       # Not OK
  6693.  
  6694.           open(FOO,"echo $foo|");  # Not OK, but...
  6695.           open(FOO,"-|") || exec 'echo', $foo;    # OK
  6696.  
  6697.           $zzz = `echo $foo`;      # Insecure, zzz tainted
  6698.  
  6699.           unlink $abc,$foo;        # Insecure
  6700.           umask $foo;              # Insecure
  6701.  
  6702.           exec "echo $foo";        # Insecure
  6703.           exec "echo", $foo;       # Secure (doesn't use sh)
  6704.           exec "sh", '-c', $foo;   # Considered secure, alas
  6705.  
  6706.      The taintedness is associated with each scalar value, so
  6707.      some elements of an array can be tainted, and others not.
  6708.  
  6709.      If you try to do something insecure, you will get a fatal
  6710.      error saying something like "Insecure dependency" or
  6711.      "Insecure PATH".  Note that you can still write an insecure
  6712.      system call or exec, but only by explicitly doing something
  6713.      like the last example above.  You can also bypass the taint-
  6714.      ing mechanism by referencing subpatterns--_p_e_r_l presumes that
  6715.      if you reference a substring using $1, $2, etc, you knew
  6716.      what you were doing when you wrote the pattern:
  6717.  
  6718.           $ARGV[0] =~ /^-P(\w+)$/;
  6719.           $printer = $1;      # Not tainted
  6720.  
  6721.      This is fairly secure since \w+ doesn't match shell meta-
  6722.      characters.  Use of .+ would have been insecure, but _p_e_r_l
  6723.      doesn't check for that, so you must be careful with your
  6724.      patterns.  This is the ONLY mechanism for untainting user
  6725.      supplied filenames if you want to do file operations on them
  6726.  
  6727.  
  6728.  
  6729. Sprite v1.0                                                   102
  6730.  
  6731.  
  6732.  
  6733.  
  6734.  
  6735.  
  6736. PERL                      User Commands                      PERL
  6737.  
  6738.  
  6739.  
  6740.      (unless you make $> equal to $<).
  6741.  
  6742.      It's also possible to get into trouble with other operations
  6743.      that don't care whether they use tainted values.  Make judi-
  6744.      cious use of the file tests in dealing with any user-
  6745.      supplied filenames.  When possible, do opens and such after
  6746.      setting $> = $<.  _P_e_r_l doesn't prevent you from opening
  6747.      tainted filenames for reading, so be careful what you print
  6748.      out.  The tainting mechanism is intended to prevent stupid
  6749.      mistakes, not to remove the need for thought.
  6750.  
  6751. EENNVVIIRROONNMMEENNTT
  6752.      _P_e_r_l uses PATH in executing subprocesses, and in finding the
  6753.      script if -S is used.  HOME or LOGDIR are used if chdir has
  6754.      no argument.
  6755.  
  6756.      Apart from these, _p_e_r_l uses no environment variables, except
  6757.      to make them available to the script being executed, and to
  6758.      child processes.  However, scripts running setuid would do
  6759.      well to execute the following lines before doing anything
  6760.      else, just to keep people honest:
  6761.  
  6762.          $ENV{'PATH'} = '/bin:/usr/bin';    # or whatever you need
  6763.          $ENV{'SHELL'} = '/bin/sh' if $ENV{'SHELL'} ne '';
  6764.          $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  6765.  
  6766.  
  6767. AAUUTTHHOORR
  6768.      Larry Wall <lwall@netlabs.com>
  6769.      MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
  6770.  
  6771. FFIILLEESS
  6772.      /tmp/perl-eXXXXXX   temporary file for --ee commands.
  6773.  
  6774. SSEEEE AALLSSOO
  6775.      a2p  awk to perl translator
  6776.      s2p  sed to perl translator
  6777.  
  6778. DDIIAAGGNNOOSSTTIICCSS
  6779.      Compilation errors will tell you the line number of the
  6780.      error, with an indication of the next token or token type
  6781.      that was to be examined.  (In the case of a script passed to
  6782.      _p_e_r_l via --ee switches, each --ee is counted as one line.)
  6783.  
  6784.      Setuid scripts have additional constraints that can produce
  6785.      error messages such as "Insecure dependency".  See the sec-
  6786.      tion on setuid scripts.
  6787.  
  6788. TTRRAAPPSS
  6789.      Accustomed _a_w_k users should take special note of the follow-
  6790.      ing:
  6791.  
  6792.  
  6793.  
  6794.  
  6795. Sprite v1.0                                                   103
  6796.  
  6797.  
  6798.  
  6799.  
  6800.  
  6801.  
  6802. PERL                      User Commands                      PERL
  6803.  
  6804.  
  6805.  
  6806.      *   Semicolons are required after all simple statements in
  6807.          _p_e_r_l.  Newline is not a statement delimiter.
  6808.  
  6809.      *   Curly brackets are required on ifs and whiles.
  6810.  
  6811.      *   Variables begin with $ or @ in _p_e_r_l.
  6812.  
  6813.      *   Arrays index from 0 unless you set $[.  Likewise string
  6814.          positions in substr() and index().
  6815.  
  6816.      *   You have to decide whether your array has numeric or
  6817.          string indices.
  6818.  
  6819.      *   Associative array values do not spring into existence
  6820.          upon mere reference.
  6821.  
  6822.      *   You have to decide whether you want to use string or
  6823.          numeric comparisons.
  6824.  
  6825.      *   Reading an input line does not split it for you.  You
  6826.          get to split it yourself to an array.  And the _s_p_l_i_t
  6827.          operator has different arguments.
  6828.  
  6829.      *   The current input line is normally in $_, not $0.  It
  6830.          generally does not have the newline stripped.  ($0 is
  6831.          the name of the program executed.)
  6832.  
  6833.      *   $<digit> does not refer to fields--it refers to sub-
  6834.          strings matched by the last match pattern.
  6835.  
  6836.      *   The _p_r_i_n_t statement does not add field and record
  6837.          separators unless you set $, and $\.
  6838.  
  6839.      *   You must open your files before you print to them.
  6840.  
  6841.      *   The range operator is "..", not comma.  (The comma
  6842.          operator works as in C.)
  6843.  
  6844.      *   The match operator is "=~", not "~".  ("~" is the one's
  6845.          complement operator, as in C.)
  6846.  
  6847.      *   The exponentiation operator is "**", not "^".  ("^" is
  6848.          the XOR operator, as in C.)
  6849.  
  6850.      *   The concatenation operator is ".", not the null string.
  6851.          (Using the null string would render "/pat/ /pat/"
  6852.          unparsable, since the third slash would be interpreted
  6853.          as a division operator--the tokener is in fact slightly
  6854.          context sensitive for operators like /, ?, and <.  And
  6855.          in fact, . itself can be the beginning of a number.)
  6856.  
  6857.      *   _N_e_x_t, _e_x_i_t and _c_o_n_t_i_n_u_e work differently.
  6858.  
  6859.  
  6860.  
  6861. Sprite v1.0                                                   104
  6862.  
  6863.  
  6864.  
  6865.  
  6866.  
  6867.  
  6868. PERL                      User Commands                      PERL
  6869.  
  6870.  
  6871.  
  6872.      *   The following variables work differently
  6873.  
  6874.                 Awk               Perl
  6875.                 ARGC              $#ARGV
  6876.                 ARGV[0]           $0
  6877.                 FILENAME          $ARGV
  6878.                 FNR               $. - something
  6879.                 FS                (whatever you like)
  6880.                 NF                $#Fld, or some such
  6881.                 NR                $.
  6882.                 OFMT              $#
  6883.                 OFS               $,
  6884.                 ORS               $\
  6885.                 RLENGTH           length($&)
  6886.                 RS                $/
  6887.                 RSTART            length($`)
  6888.                 SUBSEP            $;
  6889.  
  6890.  
  6891.      *   When in doubt, run the _a_w_k construct through a2p and see
  6892.          what it gives you.
  6893.  
  6894.      Cerebral C programmers should take note of the following:
  6895.  
  6896.      *   Curly brackets are required on ifs and whiles.
  6897.  
  6898.      *   You should use "elsif" rather than "else if"
  6899.  
  6900.      *   _B_r_e_a_k and _c_o_n_t_i_n_u_e become _l_a_s_t and _n_e_x_t, respectively.
  6901.  
  6902.      *   There's no switch statement.
  6903.  
  6904.      *   Variables begin with $ or @ in _p_e_r_l.
  6905.  
  6906.      *   Printf does not implement *.
  6907.  
  6908.      *   Comments begin with #, not /*.
  6909.  
  6910.      *   You can't take the address of anything.
  6911.  
  6912.      *   ARGV must be capitalized.
  6913.  
  6914.      *   The "system" calls link, unlink, rename, etc. return
  6915.          nonzero for success, not 0.
  6916.  
  6917.      *   Signal handlers deal with signal names, not numbers.
  6918.  
  6919.      Seasoned _s_e_d programmers should take note of the following:
  6920.  
  6921.      *   Backreferences in substitutions use $ rather than \.
  6922.  
  6923.      *   The pattern matching metacharacters (, ), and | do not
  6924.  
  6925.  
  6926.  
  6927. Sprite v1.0                                                   105
  6928.  
  6929.  
  6930.  
  6931.  
  6932.  
  6933.  
  6934. PERL                      User Commands                      PERL
  6935.  
  6936.  
  6937.  
  6938.          have backslashes in front.
  6939.  
  6940.      *   The range operator is .. rather than comma.
  6941.  
  6942.      Sharp shell programmers should take note of the following:
  6943.  
  6944.      *   The backtick operator does variable interpretation
  6945.          without regard to the presence of single quotes in the
  6946.          command.
  6947.  
  6948.      *   The backtick operator does no translation of the return
  6949.          value, unlike csh.
  6950.  
  6951.      *   Shells (especially csh) do several levels of substitu-
  6952.          tion on each command line.  _P_e_r_l does substitution only
  6953.          in certain constructs such as double quotes, backticks,
  6954.          angle brackets and search patterns.
  6955.  
  6956.      *   Shells interpret scripts a little bit at a time.  _P_e_r_l
  6957.          compiles the whole program before executing it.
  6958.  
  6959.      *   The arguments are available via @ARGV, not $1, $2, etc.
  6960.  
  6961.      *   The environment is not automatically made available as
  6962.          variables.
  6963.  
  6964. EERRRRAATTAA AANNDD AADDDDEENNDDAA
  6965.      The Perl book, _P_r_o_g_r_a_m_m_i_n_g _P_e_r_l , has the following omis-
  6966.      sions and goofs.
  6967.  
  6968.      On page 5, the examples which read
  6969.  
  6970.           eval "/usr/bin/perl
  6971.  
  6972.      should read
  6973.  
  6974.           eval "exec /usr/bin/perl
  6975.  
  6976.  
  6977.      On page 195, the equivalent to the System V sum program only
  6978.      works for very small files.  To do larger files, use
  6979.  
  6980.           undef $/;
  6981.           $checksum = unpack("%32C*",<>) % 32767;
  6982.  
  6983.  
  6984.      The descriptions of alarm and sleep refer to signal
  6985.      SIGALARM.  These should refer to SIGALRM.
  6986.  
  6987.      The --00 switch to set the initial value of $/ was added to
  6988.      Perl after the book went to press.
  6989.  
  6990.  
  6991.  
  6992.  
  6993. Sprite v1.0                                                   106
  6994.  
  6995.  
  6996.  
  6997.  
  6998.  
  6999.  
  7000. PERL                      User Commands                      PERL
  7001.  
  7002.  
  7003.  
  7004.      The --ll switch now does automatic line ending processing.
  7005.  
  7006.      The qx// construct is now a synonym for backticks.
  7007.  
  7008.      $0 may now be assigned to set the argument displayed by _p_s
  7009.      (_1).
  7010.  
  7011.      The new @###.## format was omitted accidentally from the
  7012.      description on formats.
  7013.  
  7014.      It wasn't known at press time that s///ee caused multiple
  7015.      evaluations of the replacement expression.  This is to be
  7016.      construed as a feature.
  7017.  
  7018.      (LIST) x $count now does array replication.
  7019.  
  7020.      There is now no limit on the number of parentheses in a reg-
  7021.      ular expression.
  7022.  
  7023.      In double-quote context, more escapes are supported: \e, \a,
  7024.      \x1b, \c[, \l, \L, \u, \U, \E.  The latter five control
  7025.      up/lower case translation.
  7026.  
  7027.      The $$// variable may now be set to a multi-character delim-
  7028.      iter.
  7029.  
  7030.      There is now a g modifier on ordinary pattern matching that
  7031.      causes it to iterate through a string finding multiple
  7032.      matches.
  7033.  
  7034.      All of the $^X variables are new except for $^T.
  7035.  
  7036.      The default top-of-form format for FILEHANDLE is now
  7037.      FILEHANDLE_TOP rather than top.
  7038.  
  7039.      The eval {} and sort {} constructs were added in version
  7040.      4.018.
  7041.  
  7042.      The v and V (little-endian) template options for pack and
  7043.      unpack were added in 4.019.
  7044.  
  7045. BBUUGGSS
  7046.      _P_e_r_l is at the mercy of your machine's definitions of vari-
  7047.      ous operations such as type casting, atof() and sprintf().
  7048.  
  7049.      If your stdio requires an seek or eof between reads and
  7050.      writes on a particular stream, so does _p_e_r_l.  (This doesn't
  7051.      apply to sysread() and syswrite().)
  7052.  
  7053.      While none of the built-in data types have any arbitrary
  7054.      size limits (apart from memory size), there are still a few
  7055.      arbitrary limits: a given identifier may not be longer than
  7056.  
  7057.  
  7058.  
  7059. Sprite v1.0                                                   107
  7060.  
  7061.  
  7062.  
  7063.  
  7064.  
  7065.  
  7066. PERL                      User Commands                      PERL
  7067.  
  7068.  
  7069.  
  7070.      255 characters, and no component of your PATH may be longer
  7071.      than 255 if you use -S.
  7072.  
  7073.      _P_e_r_l actually stands for Pathologically Eclectic Rubbish
  7074.      Lister, but don't tell anyone I said that.
  7075.  
  7076.  
  7077.  
  7078.  
  7079.  
  7080.  
  7081.  
  7082.  
  7083.  
  7084.  
  7085.  
  7086.  
  7087.  
  7088.  
  7089.  
  7090.  
  7091.  
  7092.  
  7093.  
  7094.  
  7095.  
  7096.  
  7097.  
  7098.  
  7099.  
  7100.  
  7101.  
  7102.  
  7103.  
  7104.  
  7105.  
  7106.  
  7107.  
  7108.  
  7109.  
  7110.  
  7111.  
  7112.  
  7113.  
  7114.  
  7115.  
  7116.  
  7117.  
  7118.  
  7119.  
  7120.  
  7121.  
  7122.  
  7123.  
  7124.  
  7125. Sprite v1.0                                                   108
  7126.  
  7127.  
  7128.  
  7129.